"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 { getTomorrowHoroscope, formatLongDate } 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
|--------------------------------------------------------------------------
|
| The confirmed real response only has bot_response + numeric scores
| (relationship/career/finances/health) + lucky_color/lucky_number, so
| everything below is best-effort: only rendered when a real string
| value is actually present under one of the aliases, never faked.
|
*/

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

function getLuckyColors(value: any): string[] {
  if (Array.isArray(value)) {
    return value.map(String).map((v) => v.trim()).filter(Boolean);
  }

  if (typeof value === "string") {
    return value
      .split(/,| and /i)
      .map((v) => v.trim())
      .filter(Boolean);
  }

  return [];
}

function getTomorrowDateObject(): Date {
  const date = new Date();
  date.setDate(date.getDate() + 1);
  return date;
}

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

  const { locale } = useLanguage();

  const contentLocale = toContentLang(locale);

  const zodiacSlug = String(params.zodiac);

  const zodiac = getZodiacBySlug(zodiacSlug);

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

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

  useEffect(() => {
    if (!zodiac) {
      router.replace("/horoscope/tomorrow-horoscope/");
      return;
    }

    // Capture values after checking zodiac exists.
    // This fixes:
    // "'zodiac' is possibly 'undefined'"
    const zodiacId = zodiac.id;
    const zodiacUrl = zodiac.slug;

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

        const result = await getTomorrowHoroscope(zodiacId, contentLocale);

        // User is not logged in
        if (!result.authenticated) {
          router.replace(
            `/signin?redirect=/horoscope/tomorrow-horoscope/${zodiacUrl}`,
          );
          return;
        }

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

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

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

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

  // API did not return data
  if (!horoscope) {
    return (
      <>
      <Header />
      <main className="horoscope-page">
        <div className="horoscope-container">
          <h1 className="horoscope-title">
            {zodiac.name} Tomorrow's Horoscope
          </h1>

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

          <div className="horoscope-layout">
            <section className="horoscope-main-card">
              <h2>Tomorrow's Horoscope Not Available</h2>

              <p>
                We could not load tomorrow's horoscope. Please try again later.
              </p>
            </section>

            <HoroscopeSidebar zodiac={zodiac.slug} />
          </div>
        </div>
      </main>
      <Footer />
      </>
    );
  }

  const mood = pickText(horoscope, ["mood", "moods", "mood_text"]);

  const luckyColors = getLuckyColors(horoscope.lucky_color);

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

  const detailedCards = [
    {
      key: "love",
      label: "Love",
      color: CATEGORY_COLORS.love,
      text: pickText(horoscope, [
        "love_prediction",
        "love_text",
        "love_desc",
        "relationship_prediction",
        "relationship_text",
        "relationship_desc",
      ]),
    },
    {
      key: "career",
      label: "Career & Profession",
      color: CATEGORY_COLORS.career,
      text: pickText(horoscope, [
        "career_prediction",
        "career_text",
        "career_desc",
        "profession_prediction",
        "work_prediction",
      ]),
    },
    {
      key: "money",
      label: "Finance & Luck",
      color: CATEGORY_COLORS.money,
      text: pickText(horoscope, [
        "finance_prediction",
        "finance_text",
        "finance_desc",
        "money_prediction",
        "finances_text",
      ]),
    },
    {
      key: "health",
      label: "Health",
      color: CATEGORY_COLORS.health,
      text: pickText(horoscope, [
        "health_prediction",
        "health_text",
        "health_desc",
      ]),
    },
  ].filter((card) => card.text);

  return (
    <>
    <Header />
    <main className="horoscope-page">
      <div className="horoscope-container">
        {/* Page title */}
        <h1 className="horoscope-title">{zodiac.name} Tomorrow's Horoscope</h1>

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

        <div className="horoscope-layout">
          {/* Main 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} Horoscope Tomorrow</h2>

                <div className="horoscope-meta">
                  <span>{formatLongDate(getTomorrowDateObject())}</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>

                  {mood && (
                    <>
                      <span className="meta-dot">·</span>
                      <span>Mood: {mood}</span>
                    </>
                  )}
                </div>
              </div>
            </div>

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

            {/* Scores */}
            <div className="score-grid">
              <ScoreBar
                label="Love"
                value={horoscope.relationship}
                color={CATEGORY_COLORS.love}
              />

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

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

            {/* Lucky information */}
            <div className="lucky-section">
              <h3>Tomorrow's Insights</h3>

              <div className="lucky-grid">
                {/* Mood */}
                {mood && (
                  <div>
                    <span>Mood</span>
                    <strong>{mood}</strong>
                  </div>
                )}

                {/* Lucky Color */}
                <div>
                  <span>
                    Lucky Colour{luckyColors.length > 1 ? "s" : ""}
                  </span>

                  <strong className="lucky-color-value">
                    {luckyColors.map((color) => (
                      <span
                        key={color}
                        className="lucky-swatch"
                        style={{ background: color.toLowerCase() }}
                        title={color}
                      />
                    ))}

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

                {/* Lucky Number */}
                <div>
                  <span>Lucky Number</span>

                  <strong>
                    {Array.isArray(horoscope.lucky_number)
                      ? horoscope.lucky_number.join(", ")
                      : horoscope.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>

        {/* Detailed reading */}
        {detailedCards.length > 0 && (
          <section className="horoscope-detailed-section">
            <h2 className="horoscope-detailed-title">Detailed Reading</h2>

            <div className="horoscope-detailed-grid">
              {detailedCards.map((card) => (
                <div
                  className="horoscope-detailed-card"
                  key={card.key}
                  style={{ borderTopColor: card.color }}
                >
                  <span
                    className="horoscope-detailed-label"
                    style={{ color: card.color }}
                  >
                    {card.label}
                  </span>

                  <p>{card.text}</p>
                </div>
              ))}
            </div>
          </section>
        )}

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