"use client";

import { useState } from "react";

import Header from "@/app/components/layout/Header";
import Footer from "@/app/components/layout/Footer";

import PanchangSearchBar from "@/app/components/panchang/PanchangSearchBar";
import PanchangRelatedPages from "@/app/components/panchang/PanchangRelatedPages";
import PanchangSunMoonCards from "@/app/components/panchang/PanchangSunMoonCards";
import PanchangDetailsTable from "@/app/components/panchang/PanchangDetailsTable";
import ChoghadiyaTable from "@/app/components/panchang/ChoghadiyaTable";

import { DEFAULT_PANCHANG_LOCATION, getTodayDate, PanchangLocation } from "@/app/lib/panchang";

import { usePanchangData } from "@/app/lib/usePanchangData";

import { ChoghadiyaRow } from "@/app/lib/panchangParse";

import "@/app/panchang/panchang.css";

const LEGEND: { label: string; nature: string }[] = [
  { label: "Good", nature: "good" },
  { label: "Neutral", nature: "neutral" },
  { label: "Bad", nature: "bad" },
  { label: "Evil", nature: "evil" },
];

function findCurrentChoghadiya(
  day: ChoghadiyaRow[],
  night: ChoghadiyaRow[],
): ChoghadiyaRow | undefined {
  const now = Date.now();

  return [...day, ...night].find((row) => {
    if (!row.start || !row.end) return false;

    const start = new Date(row.start).getTime();
    const end = new Date(row.end).getTime();

    return !Number.isNaN(start) && !Number.isNaN(end) && now >= start && now < end;
  });
}

const CHOGHADIYA_LIST: { name: string; nature: string; meaning: string }[] = [
  { name: "Amrit", nature: "good", meaning: "The most favourable slot — good for any important or new work." },
  { name: "Shubh", nature: "good", meaning: "Auspicious — favourable for ceremonies and new beginnings." },
  { name: "Labh", nature: "good", meaning: "Associated with gain — good for business and financial matters." },
  { name: "Chal", nature: "neutral", meaning: "Mixed results — acceptable for travel and routine work." },
  { name: "Rog", nature: "bad", meaning: "Associated with conflict or illness — best avoided for new starts." },
  { name: "Kaal", nature: "bad", meaning: "An inauspicious slot — avoid starting important work." },
  { name: "Udveg", nature: "bad", meaning: "Associated with anxiety or unrest — not ideal for new ventures." },
];

export default function ChoghadiyaPage() {
  const [activeDate, setActiveDate] = useState(getTodayDate());

  const [activeLocation, setActiveLocation] = useState<PanchangLocation>(DEFAULT_PANCHANG_LOCATION);

  const [activeLocationLabel, setActiveLocationLabel] = useState(DEFAULT_PANCHANG_LOCATION.label);

  const { loading, error, dateLabel, choghadiyaRows, derivedSunMoon, derivedToday, samvatRows } =
    usePanchangData(activeDate, activeLocation, "/panchang/choghadiya");

  const current = findCurrentChoghadiya(choghadiyaRows.day, choghadiyaRows.night);

  if (loading) {
    return (
      <>
        <Header />
        <main className="horoscope-loading">Loading Choghadiya...</main>
        <Footer />
      </>
    );
  }

  return (
    <>
      <Header />

      <main className="panchang-page">
        <div className="panchang-container">
          <div className="panchang-hero">
            <h1>
              <span className="panchang-hero-accent">Today&apos;s Choghadiya</span>
            </h1>

            <PanchangSearchBar
              date={activeDate}
              onDateChange={setActiveDate}
              location={activeLocation}
              locationLabel={activeLocationLabel}
              onLocationChange={(location, label) => {
                setActiveLocation(location);
                setActiveLocationLabel(label);
              }}
              buttonLabel="Get Choghadiya"
            />

            <div className="panchang-summary-row">
              <span className="panchang-location">📍 {activeLocationLabel}</span>

              <span className="panchang-date-label">{dateLabel}</span>
            </div>
          </div>

          {error && <div className="panchang-error">{error}</div>}

          {/* CURRENT CHOGHADIYA */}

          {current && (
            <div className="choghadiya-now-card">
              <span className="choghadiya-now-icon">⏰</span>

              <div>
                <span className="choghadiya-now-label">Current Choghadiya</span>

                <span>
                  <span className={`choghadiya-now-name choghadiya-color ${current.nature}`}>
                    {current.name}
                  </span>

                  <span className="choghadiya-now-time">{current.time}</span>

                  {current.nature && (
                    <span className={`choghadiya-now-time choghadiya-color ${current.nature}`}>
                      ({current.nature.charAt(0).toUpperCase() + current.nature.slice(1)})
                    </span>
                  )}
                </span>
              </div>
            </div>
          )}

          {/* CHOGHADIYA TABLES */}

          {choghadiyaRows.day.length > 0 || choghadiyaRows.night.length > 0 ? (
            <>
              <div className="panchang-two-col">
                {choghadiyaRows.day.length > 0 && (
                  <section className="panchang-section-card accent-yellow">
                    <h2>Day Choghadiya</h2>

                    <ChoghadiyaTable rows={choghadiyaRows.day} />
                  </section>
                )}

                {choghadiyaRows.night.length > 0 && (
                  <section className="panchang-section-card">
                    <h2>Night Choghadiya</h2>

                    <ChoghadiyaTable rows={choghadiyaRows.night} />
                  </section>
                )}
              </div>

              <div className="choghadiya-legend">
                <span className="choghadiya-legend-label">Legend:</span>

                {LEGEND.map((item) => (
                  <span className="choghadiya-legend-item" key={item.nature}>
                    <span className={`choghadiya-legend-dot ${item.nature}`} />
                    {item.label}
                  </span>
                ))}
              </div>
            </>
          ) : (
            <section className="panchang-section-card accent-yellow">
              <h2>Choghadiya Muhurta</h2>

              <p className="panchang-empty">Choghadiya timings are unavailable right now.</p>
            </section>
          )}

          {/* SUN / MOON TIMING CARDS */}

          <PanchangSunMoonCards derivedSunMoon={derivedSunMoon} />

          {/* PANCHANG DETAILS + SAMVAT */}

          <PanchangDetailsTable derivedToday={derivedToday} samvatRows={samvatRows} />

          {/* EDUCATIONAL CONTENT */}

          <section className="panchang-section-card panchang-edu-section">
            <h2>What Is Choghadiya and How Is It Used?</h2>

            <p>
              Choghadiya (also spelled Chaughadiya) divides daylight and night-time into eight
              equal slots each, giving 16 windows across the full day. Every slot carries one of
              seven traditional labels — Amrit, Shubh, Labh, Chal, Rog, Kaal, and Udveg — each
              considered favourable, neutral, or inauspicious for starting new work.
            </p>

            <p>
              It&apos;s one of the simplest muhurat systems to use day-to-day: rather than
              calculating exact planetary positions, you just check which named slot the current
              time falls in before travelling, starting a task, or making a purchase.
            </p>

            <h3>The Seven Choghadiya Types</h3>

            <div className="panchang-table-wrap">
              <table className="panchang-table">
                <thead>
                  <tr>
                    <th>Choghadiya</th>
                    <th>Nature</th>
                    <th>Meaning</th>
                  </tr>
                </thead>

                <tbody>
                  {CHOGHADIYA_LIST.map((item) => (
                    <tr key={item.name}>
                      <td>
                        <strong>{item.name}</strong>
                      </td>
                      <td>
                        <span className={`choghadiya-nature ${item.nature}`}>{item.nature}</span>
                      </td>
                      <td>{item.meaning}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </section>

          <PanchangRelatedPages current="/panchang/choghadiya" />
        </div>
      </main>

      <Footer />
    </>
  );
}
