"use client";

import { useEffect, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import Link from "@/app/components/LocaleLink";
import Header from "@/app/components/layout/Header";
import Footer from "@/app/components/layout/Footer";
import ZodiacNavigation from "@/app/components/horoscope/ZodiacNavigation";
import YearlyHoroscope from "@/app/components/horoscope/YearlyHoroscope";
import HoroscopeSidebar from "@/app/components/horoscope/HoroscopeSidebar";
import HoroscopeFeedback from "@/app/components/horoscope/HoroscopeFeedback";

import { getZodiacBySlug } from "@/app/lib/zodiac";
import { useZodiacSigns } from "@/app/lib/useZodiacSigns";
import ZodiacImage from "@/app/components/horoscope/ZodiacImage";
import { getYearlyHoroscope } from "@/app/lib/horoscope";
import { useLanguage } from "@/app/context/LanguageContext";
import { toContentLang } from "@/app/i18n/locales";

/*
|--------------------------------------------------------------------------
| Element accent
|--------------------------------------------------------------------------
*/

const ELEMENT_COLORS: Record<string, string> = {
  FIRE: "#e14b3d",
  EARTH: "#4d9d5d",
  AIR: "#6b7fd7",
  WATER: "#3fa9c9",
};

/*
|--------------------------------------------------------------------------
| Defensive field helpers
|--------------------------------------------------------------------------
|
| Nothing about the yearly response shape is confirmed real yet — the
| existing quarterly (phase_1..4) shape in YearlyHoroscope.tsx was
| itself a guess. So this tries a life-area breakdown (matching the
| astrotalk reference) first, and only falls back to the quarterly
| component if none of those fields are actually present, rather than
| assuming either guess is correct.
|
*/

function pickText(
  source: any,
  keys: string[]
): string | undefined {
  for (const key of keys) {
    const value = source?.[key];

    if (typeof value === "string" && value.trim()) {
      return value.trim();
    }
  }

  return undefined;
}

export default function YearlyHoroscopePage() {
  const params = useParams();
  const router = useRouter();

  const { locale } = useLanguage();

  const contentLocale = toContentLang(locale);

  const slug = String(params.zodiac);

  const zodiac = getZodiacBySlug(slug);

  const { signs, imagesLoaded } = useZodiacSigns();
  const zodiacImage = signs.find((s) => s.slug === slug)?.svgImage;

  const [data, setData] = useState<any>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    /*
     * Check zodiac first
     */
    if (!zodiac) {
      router.replace("/horoscope/yearly-horoscope/");
      return;
    }

    /*
     * Capture values after null check.
     *
     * This fixes:
     * 'zodiac' is possibly 'undefined'
     */
    const zodiacId = zodiac.id;
    const zodiacSlug = zodiac.slug;

    async function load() {
      try {
        setLoading(true);

        const year = new Date().getFullYear();

        const result = await getYearlyHoroscope(
          zodiacId,
          year,
          contentLocale
        );

        /*
         * User is not authenticated
         */
        if (!result.authenticated) {
          router.replace(
            `/signin?redirect=/horoscope/yearly-horoscope/${zodiacSlug}`
          );
          return;
        }

        /*
         * API response
         */
        if (result.success) {
          setData(result.data?.data ?? null);
        } else {
          setData(null);
        }
      } catch (error) {
        console.error(
          "Failed to load yearly horoscope:",
          error
        );

        setData(null);
      } finally {
        setLoading(false);
      }
    }

    load();
  }, [zodiac, router, contentLocale]);

  /*
   * Invalid zodiac / loading
   */
  if (!zodiac || loading) {
    return (
      <>
      <Header />
      <main className="horoscope-loading">
        Loading yearly horoscope...
      </main>
      <Footer />
      </>
    );
  }

  /*
   * No API data
   */
  if (!data) {
    return (
      <>
      <Header />
      <main className="horoscope-page">
        <div className="horoscope-container">

          <h1 className="horoscope-title">
            {zodiac.name} Yearly Horoscope{" "}
            {new Date().getFullYear()}
          </h1>

          <ZodiacNavigation
            type="yearly-horoscope"
            activeZodiac={zodiac.slug}
          />

          <div className="horoscope-layout">

            <section className="horoscope-main-card">
              <h2>
                Yearly Horoscope Not Available
              </h2>

              <p>
                We could not load the yearly
                horoscope. Please try again later.
              </p>
            </section>

            <HoroscopeSidebar
              zodiac={zodiac.slug}
            />

          </div>
        </div>
      </main>
      <Footer />
      </>
    );
  }

  const elementColor = ELEMENT_COLORS[zodiac.element] || "#7144d7";

  const year = new Date().getFullYear();

  const lifeAreas = [
    {
      key: "love",
      label: "Love and Relationships",
      text: pickText(data, [
        "love_prediction",
        "love_text",
        "relationship_prediction",
        "relationship_text",
      ]),
      keyMonth: pickText(data, [
        "love_key_month",
        "relationship_key_month",
        "love_month",
      ]),
    },
    {
      key: "health",
      label: "Health and Wellness",
      text: pickText(data, [
        "health_prediction",
        "health_text",
      ]),
      keyMonth: pickText(data, [
        "health_key_month",
        "health_month",
      ]),
    },
    {
      key: "career",
      label: "Career and Education",
      text: pickText(data, [
        "career_prediction",
        "career_text",
      ]),
      keyMonth: pickText(data, [
        "career_key_month",
        "career_month",
      ]),
    },
    {
      key: "money",
      label: "Money and Finances",
      text: pickText(data, [
        "finance_prediction",
        "finance_text",
        "money_prediction",
        "finances_text",
      ]),
      keyMonth: pickText(data, [
        "finance_key_month",
        "money_key_month",
        "finance_month",
      ]),
    },
  ].filter((area) => area.text);

  const yearlyTip = pickText(data, [
    "tip_of_the_year",
    "yearly_tip",
    "tip",
  ]);

  const closingMessage = pickText(data, [
    "closing_message",
    "conclusion",
    "wish",
  ]);

  return (
    <>
    <Header />
    <main className="horoscope-page">
      <div className="horoscope-container">

        {/* Page title */}
        <h1 className="horoscope-title">
          {zodiac.name} Yearly Horoscope{" "}
          {year}
        </h1>

        {/* Zodiac navigation */}
        <ZodiacNavigation
          type="yearly-horoscope"
          activeZodiac={zodiac.slug}
        />

        <div className="horoscope-layout">

          {lifeAreas.length > 0 ? (
            <section className="horoscope-main-card">

              {/* Header */}
              <div className="horoscope-header">

                <div
                  className="large-zodiac-icon"
                >
                  <ZodiacImage svgImage={zodiacImage} symbol={zodiac.symbol} name={zodiac.name} loading={!imagesLoaded} />
                </div>

                <div>
                  <h2>
                    {zodiac.name} Yearly Horoscope
                  </h2>

                  <div className="horoscope-meta">
                    <span>{year}</span>

                    <span className="meta-dot">·</span>

                    <span>{zodiac.date}</span>

                    <span className="meta-dot">·</span>

                    <span
                      className="element-badge"
                      style={{
                        background: `${elementColor}22`,
                        color: elementColor,
                      }}
                    >
                      {zodiac.element}
                    </span>
                  </div>
                </div>

              </div>

              {/* Life area breakdown */}
              <div className="horoscope-subsections">
                {lifeAreas.map((area) => (
                  <div className="horoscope-subsection" key={area.key}>
                    <h3>{area.label}</h3>

                    <p>{area.text}</p>

                    {area.keyMonth && (
                      <p className="horoscope-key-month">
                        <strong>Key Month:</strong> {area.keyMonth}
                      </p>
                    )}
                  </div>
                ))}
              </div>

              {yearlyTip && (
                <div className="horoscope-yearly-tip">
                  <h3>Tip of the Month for the Year:</h3>
                  <p>&ldquo;{yearlyTip}&rdquo;</p>
                </div>
              )}

              {closingMessage && (
                <p className="horoscope-yearly-closing">
                  {closingMessage}
                </p>
              )}

              {/* Actions */}
              <div className="horoscope-actions">
                <Link
                  href="/talk-to-astrologer"
                  className="horoscope-action-btn primary"
                >
                  Talk to {zodiac.name} Expert
                </Link>

                <Link
                  href="/free-kundli"
                  className="horoscope-action-btn secondary"
                >
                  Get Free Kundli
                </Link>

                <Link
                  href="/kundli-matching"
                  className="horoscope-action-btn secondary"
                >
                  Match with Partner
                </Link>
              </div>

            </section>
          ) : (
            /* Fall back to the quarterly breakdown when no life-area fields are present */
            <YearlyHoroscope data={data} />
          )}

          {/* Sidebar */}
          <HoroscopeSidebar
            zodiac={zodiac.slug}
          />

        </div>

        <HoroscopeFeedback zodiacId={zodiac.id} horoscopeType="yearly" />
      </div>
    </main>
    <Footer />
    </>
  );
}
