"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 {
  getDailyHoroscope,
  getTodayDate,
  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 [];
}

export default function DailyZodiacPage() {
  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(() => {
    // Invalid zodiac
    if (!zodiac) {
      router.replace("/horoscope/daily-horoscope/");
      return;
    }

    // IMPORTANT:
    // Capture these values after the zodiac null check.
    // This prevents the production TypeScript error.
    const zodiacId = zodiac.id;
    const zodiacUrl = zodiac.slug;

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

        const result = await getDailyHoroscope(
          zodiacId,
          getTodayDate(),
          contentLocale
        );

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

        // API failed
        if (!result.success) {
          setHoroscope(null);
          return;
        }

        // API response:
        // result.data.data
        setHoroscope(result.data?.data ?? null);
      } catch (error) {
        console.error(
          "Failed to load daily horoscope:",
          error
        );

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

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

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

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

  /*
   * API returned no horoscope
   */
  if (!horoscope) {
    return (
      <>
      <Header />
      <main className="horoscope-page">
        <div className="horoscope-container">
          <h1 className="horoscope-title">
            {zodiac.name} Daily Horoscope
          </h1>

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

          <div className="horoscope-layout">
            <section className="horoscope-main-card">
              <h2>Horoscope not available</h2>

              <p>
                We could not load today'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} Daily Horoscope
        </h1>

        {/* ZODIAC NAVIGATION */}
        <ZodiacNavigation
          type="daily-horoscope"
          activeZodiac={zodiac.slug}
        />

        <div className="horoscope-layout">

          {/* MAIN CONTENT */}
          <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 Today
                </h2>

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

            {/* 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>
                Today'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 />
    </>
  );
}
