"use client";

import { useState } from "react";

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

import { usePanchangData } from "@/app/lib/usePanchangData";
import { useLanguage } from "@/app/context/LanguageContext";
import { toContentLang } from "@/app/i18n/locales";

import { formatMuhuratRange, formatPanchangElement } from "@/app/lib/panchangParse";

import PanchangSearchBar from "./PanchangSearchBar";
import PanchangSunMoonCards from "./PanchangSunMoonCards";
import PanchangDetailsTable from "./PanchangDetailsTable";
import PanchangRelatedPages from "./PanchangRelatedPages";
import ChoghadiyaTable from "./ChoghadiyaTable";
import HoraTable from "./HoraTable";

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

interface Props {
  /** e.g. "Today Panchang" / "Tomorrow Panchang" — "(Panchangam)" is appended automatically. */
  title: string;
  date: string;
  redirectPath: string;
  currentPage: string;
}

/*
|--------------------------------------------------------------------------
| Component
|--------------------------------------------------------------------------
*/

export default function PanchangDashboard({ title, date, redirectPath, currentPage }: Props) {
  const { locale } = useLanguage();

  const [activeDate, setActiveDate] = useState(date);

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

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

  const {
    loading,
    error,
    derivedToday,
    derivedSunMoon,
    dateLabel,
    choghadiyaRows,
    horaRows,
    festivals,
    muhuratRows,
    balamRows,
    samvatRows,
    planetRows,
  } = usePanchangData(activeDate, activeLocation, redirectPath);

  if (loading) {
    return <main className="horoscope-loading">Loading {title.toLowerCase()}...</main>;
  }

  return (
    <main className="panchang-page">
      <div className="panchang-container">
        {/* HERO */}

        <div className="panchang-hero">
          <h1>
            <span className="panchang-hero-accent">{title}</span>{" "}
            <span className="panchang-hero-sub">(Panchangam)</span>
          </h1>

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

          <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>}

        {/* SUN / MOON TIMING CARDS */}

        <PanchangSunMoonCards derivedSunMoon={derivedSunMoon} />

        {/* PANCHANG DETAILS + SAMVAT */}

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

        {/* INAUSPICIOUS TIMINGS */}

        <section id="panchang-muhurat" className="panchang-section-card accent-red">
          <h2>
            Inauspicious Timings <span className="panchang-heading-sub">(Ashubha Muhurat)</span>
          </h2>

          {muhuratRows.length > 0 ? (
            <table className="panchang-kv-table panchang-muhurat-table">
              <tbody>
                {muhuratRows.map((row) => (
                  <tr key={row.label}>
                    <td className="panchang-kv-label">{row.label}</td>
                    <td className="panchang-kv-value panchang-muhurat-range">
                      {formatMuhuratRange(row.value)}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          ) : (
            <p className="panchang-empty">Inauspicious timings are unavailable right now.</p>
          )}
        </section>

        {/* CHANDRABALAM & TARABALAM */}

        <section className="panchang-section-card accent-yellow">
          <h2>Chandrabalam &amp; Tarabalam</h2>

          {balamRows.length > 0 ? (
            <table className="panchang-kv-table">
              <tbody>
                {balamRows.map((row) => (
                  <tr key={row.label}>
                    <td className="panchang-kv-label">{row.label}</td>
                    <td className="panchang-kv-value">{formatPanchangElement(row.value)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          ) : (
            <p className="panchang-empty">Chandrabalam &amp; Tarabalam are unavailable right now.</p>
          )}
        </section>

        {/* PLANETARY POSITIONS */}

        <section className="panchang-section-card accent-yellow">
          <h2>Planetary Positions</h2>

          {planetRows.length > 0 ? (
            <div className="panchang-table-wrap">
              <table className="panchang-table">
                <thead>
                  <tr>
                    <th>Planets</th>
                    <th>Rashi</th>
                    <th>Longitude</th>
                    <th>Nakshatra</th>
                    <th>Pada</th>
                  </tr>
                </thead>

                <tbody>
                  {planetRows.map((row) => (
                    <tr key={row.name}>
                      <td>
                        <strong>{row.name}</strong>
                      </td>
                      <td>{row.rashi}</td>
                      <td>{row.longitude}</td>
                      <td>{row.nakshatra}</td>
                      <td>{row.pada}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          ) : (
            <p className="panchang-empty">
              Current planetary positions are not available from the daily panchang yet.
            </p>
          )}
        </section>

        {/* LAGNA CHART + RELATED PAGES */}

        <div className="panchang-two-col panchang-chart-row">
          <section className="panchang-section-card">
            <h2>Lagna Chart</h2>

            <div className="panchang-chart-wrap">
              <img
                src={getPanchangChartImageUrl(activeDate, activeLocation, "north", toContentLang(locale))}
                alt="Lagna Chart"
                loading="lazy"
              />
            </div>
          </section>

          <PanchangRelatedPages current={currentPage} />
        </div>

        {/* CHOGHADIYA */}

        {(choghadiyaRows.day.length > 0 || choghadiyaRows.night.length > 0) && (
          <section id="panchang-choghadiya" className="panchang-section-card">
            <h2>Choghadiya Muhurta</h2>

            {choghadiyaRows.day.length > 0 && (
              <>
                <h3 className="panchang-subheading">Day Choghadiya</h3>

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

            {choghadiyaRows.night.length > 0 && (
              <>
                <h3 className="panchang-subheading">Night Choghadiya</h3>

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

        {/* HORA */}

        {horaRows.length > 0 && (
          <section id="panchang-hora" className="panchang-section-card">
            <h2>Hora Muhurta</h2>

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

        {/* FESTIVALS */}

        {festivals.length > 0 && (
          <section className="panchang-section-card">
            <h2>Festivals &amp; Vrats</h2>

            <div className="panchang-festival-list">
              {festivals.map((item, index) => (
                <div className="panchang-festival-item" key={`${item.name}-${index}`}>
                  <strong>{item.name}</strong>

                  {item.description && <span>{item.description}</span>}
                </div>
              ))}
            </div>
          </section>
        )}
      </div>
    </main>
  );
}
