"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 ScoreBar from "@/app/components/horoscope/ScoreBar";
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 {
  getWeeklyHoroscope,
  getThisWeekRange,
  formatWeekRange,
} from "@/app/lib/horoscope";
import { useLanguage } from "@/app/context/LanguageContext";
import { toContentLang } from "@/app/i18n/locales";

/*
|--------------------------------------------------------------------------
| Category accents
|--------------------------------------------------------------------------
*/

const CATEGORY_COLORS = {
  love: "#ff5c8d",
  career: "#8b5cf6",
  money: "#22c55e",
  health: "#f5a623",
};

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

/*
|--------------------------------------------------------------------------
| Defensive field helpers
|--------------------------------------------------------------------------
|
| Only the numeric scores + bot_response + lucky_color/lucky_number are
| confirmed real fields. The narrative Personal/Money/Health/Love
| subsections below are best-effort alias lookups — if none of them
| match, the section falls back to the (confirmed real) score bars
| instead of showing nothing.
|
*/

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 WeeklyHoroscopePage() {
  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/weekly-horoscope/");
      return;
    }

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

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

        const result = await getWeeklyHoroscope(
          zodiacId,
          contentLocale
        );

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

          return;
        }

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

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

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

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

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

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

          <h1 className="horoscope-title">
            {zodiac.name} Weekly Horoscope
          </h1>

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

          <div className="horoscope-layout">

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

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

            <HoroscopeSidebar
              zodiac={zodiac.slug}
            />

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

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

  const { start, end } = getThisWeekRange();

  const subsections = [
    {
      key: "personal",
      label: "Personal",
      text: pickText(data, [
        "personal_prediction",
        "personal_text",
        "personal",
      ]),
    },
    {
      key: "money",
      label: "Money",
      text: pickText(data, [
        "money_prediction",
        "money_text",
        "finance_prediction",
        "finance_text",
        "finances_text",
      ]),
    },
    {
      key: "health",
      label: "Health",
      text: pickText(data, [
        "health_prediction",
        "health_text",
        "health_desc",
      ]),
    },
    {
      key: "love",
      label: "Love",
      text: pickText(data, [
        "love_prediction",
        "love_text",
        "relationship_prediction",
        "relationship_text",
      ]),
    },
  ].filter((section) => section.text);

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

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

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

        <div className="horoscope-layout">

          {/* Main horoscope card */}
          <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} Weekly Horoscope
                </h2>

                <div className="horoscope-meta">
                  <span>{formatWeekRange(start, end)}</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>

            {/* Description */}
            <div className="horoscope-description">
              {data.bot_response}
            </div>

            {/* Narrative subsections, when the real response has them */}
            {subsections.length > 0 && (
              <div className="horoscope-subsections">
                {subsections.map((section) => (
                  <div className="horoscope-subsection" key={section.key}>
                    <h3>{section.label}:</h3>
                    <p>{section.text}</p>
                  </div>
                ))}
              </div>
            )}

            {/* Scores — shown whenever the narrative subsections above aren't available */}
            {subsections.length === 0 && (
              <div className="score-grid">

                <ScoreBar
                  label="Love"
                  value={data.relationship}
                  color={CATEGORY_COLORS.love}
                />

                <ScoreBar
                  label="Career"
                  value={data.career}
                  color={CATEGORY_COLORS.career}
                />

                <ScoreBar
                  label="Money"
                  value={data.finances}
                  color={CATEGORY_COLORS.money}
                />

                <ScoreBar
                  label="Health"
                  value={data.health}
                  color={CATEGORY_COLORS.health}
                />

                {typeof data.travel !== "undefined" && (
                  <ScoreBar label="Travel" value={data.travel} />
                )}

                {typeof data.family !== "undefined" && (
                  <ScoreBar label="Family" value={data.family} />
                )}

              </div>
            )}

            {/* Weekly Insights */}
            <div className="lucky-section">

              <h3>
                Weekly Insights
              </h3>

              <div className="lucky-grid">

                <div>
                  <span>Lucky Colour</span>

                  <strong>
                    {data.lucky_color}
                  </strong>
                </div>

                <div>
                  <span>Lucky Number</span>

                  <strong>
                    {Array.isArray(
                      data.lucky_number
                    )
                      ? data.lucky_number.join(", ")
                      : data.lucky_number}
                  </strong>
                </div>

              </div>

            </div>

            {/* 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>

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

        </div>

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