"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 HoraTable from "@/app/components/panchang/HoraTable";

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

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

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

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

function findCurrentHora(rows: HoraRow[]): HoraRow | undefined {
  const now = Date.now();

  return rows.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 HORA_LIST: { planet: string; meaning: string }[] = [
  { planet: "Sun", meaning: "Authority, government work, and matters needing confidence." },
  { planet: "Moon", meaning: "Travel, emotional matters, and dealing with the public." },
  { planet: "Mars", meaning: "Competition, courage, sports, and property matters." },
  { planet: "Mercury", meaning: "Communication, business deals, writing, and learning." },
  { planet: "Jupiter", meaning: "Education, spirituality, finance, and important ceremonies." },
  { planet: "Venus", meaning: "Relationships, art, luxury purchases, and creative work." },
  { planet: "Saturn", meaning: "Labour-intensive or long-term work requiring patience." },
];

export default function HoraPage() {
  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, horaRows, derivedSunMoon, derivedToday, samvatRows } =
    usePanchangData(activeDate, activeLocation, "/panchang/hora");

  // Classical Hora divides day + night into 12 equal slots each — the
  // API returns one flat 24-item list starting at sunrise, so the
  // first 12 are Day Hora and the rest are Night Hora.
  const dayHora = horaRows.slice(0, 12);

  const nightHora = horaRows.slice(12);

  const current = findCurrentHora(horaRows);

  if (loading) {
    return (
      <>
        <Header />
        <main className="horoscope-loading">Loading Hora...</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 Hora</span>
            </h1>

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

            <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 HORA */}

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

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

                <span>
                  <span className={`choghadiya-now-name hora-planet ${current.lord.toLowerCase()}`}>
                    {current.lord}
                  </span>

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

          {/* HORA TABLES */}

          {horaRows.length > 0 ? (
            <div className="panchang-two-col">
              {dayHora.length > 0 && (
                <section className="panchang-section-card accent-yellow">
                  <h2>Day Hora</h2>

                  <HoraTable rows={dayHora} />
                </section>
              )}

              {nightHora.length > 0 && (
                <section className="panchang-section-card">
                  <h2>Night Hora</h2>

                  <HoraTable rows={nightHora} />
                </section>
              )}
            </div>
          ) : (
            <section className="panchang-section-card accent-yellow">
              <h2>Hora Muhurta</h2>

              <p className="panchang-empty">Hora 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 Hora and How Is It Used?</h2>

            <p>
              Hora divides both daylight and night-time into 12 equal hours each, and assigns
              every one of those 24 slots to one of the seven classical planets, always starting
              with the ruling planet of that weekday. Unlike Choghadiya (which repeats a 7-name
              cycle), Hora always runs through all seven planets in the same fixed order —
              Sun, Venus, Mercury, Moon, Saturn, Jupiter, Mars — repeating as needed to fill the
              day.
            </p>

            <p>
              It&apos;s commonly used to pick a favourable time for planet-specific activities —
              a Mercury hora for signing a business deal, a Venus hora for something creative or
              relationship-related, and so on.
            </p>

            <h3>What Each Planetary Hora Favours</h3>

            <div className="panchang-table-wrap">
              <table className="panchang-table">
                <thead>
                  <tr>
                    <th>Planet</th>
                    <th>Favourable For</th>
                  </tr>
                </thead>

                <tbody>
                  {HORA_LIST.map((item) => (
                    <tr key={item.planet}>
                      <td>
                        <strong>{item.planet}</strong>
                      </td>
                      <td>{item.meaning}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </section>

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

      <Footer />
    </>
  );
}
