import type { Metadata } from "next";
import Link from "next/link";
import { Sparkles, Briefcase, Coins, Heart, Activity, AlertTriangle } from "lucide-react";
import { ZODIAC, zodiacBySlug, zodiacFromYear } from "@/lib/zodiac";
import { yearOutlook } from "@/lib/year-outlook";
import { AiInsightPanel } from "@/components/ai/insight-panel";

export const metadata: Metadata = {
  title: "12 Con Giáp — Vận Năm — Tử Vi Số",
  description:
    "Tra cứu tính cách, sự nghiệp, tình yêu, vận hạn năm hiện tại của 12 con giáp theo năm sinh.",
};

type Props = { searchParams: Promise<{ slug?: string; year?: string; refYear?: string }> };

export default async function ZodiacPage({ searchParams }: Props) {
  const sp = await searchParams;
  const year = sp.year ? parseInt(sp.year, 10) : null;
  const fromYear = year && year > 1900 && year < 2200 ? zodiacFromYear(year) : null;
  const selected = sp.slug ? zodiacBySlug(sp.slug) : fromYear;

  const refYear = sp.refYear ? parseInt(sp.refYear, 10) : new Date().getFullYear();
  const outlook = selected ? yearOutlook(selected.slug, refYear) : null;

  return (
    <div className="bg-bg-base min-h-screen">
      <div className="mx-auto max-w-5xl px-4 py-8 lg:py-12">
        <div className="mb-8 text-center">
          <h1 className="font-display text-ink-primary text-3xl font-semibold lg:text-4xl">
            12 Con Giáp
          </h1>
          <p className="text-ink-secondary mt-2 text-sm">
            Tính cách · sự nghiệp · tình yêu · vận hạn năm — chọn theo tuổi hoặc năm sinh.
          </p>
        </div>

        <form
          method="GET"
          className="border-stroke-subtle bg-bg-elevated/40 mx-auto mb-8 grid max-w-md gap-3 rounded-xl border p-4 sm:grid-cols-2"
        >
          <div>
            <label className="text-ink-muted block text-xs">Năm sinh dương lịch</label>
            <input
              type="number"
              name="year"
              defaultValue={year ?? ""}
              placeholder="vd: 1992"
              min={1900}
              max={2100}
              className="bg-bg-inset border-stroke-default text-ink-primary focus:border-brand-gold mt-1 w-full rounded-md border px-3 py-2 text-sm focus:outline-none"
            />
          </div>
          <div>
            <label className="text-ink-muted block text-xs">Xem vận năm</label>
            <input
              type="number"
              name="refYear"
              defaultValue={refYear}
              min={1900}
              max={2200}
              className="bg-bg-inset border-stroke-default text-ink-primary focus:border-brand-gold mt-1 w-full rounded-md border px-3 py-2 text-sm focus:outline-none"
            />
          </div>
          {sp.slug ? <input type="hidden" name="slug" value={sp.slug} /> : null}
          <button
            type="submit"
            className="bg-brand-gold text-bg-base rounded-md px-4 py-2 text-sm font-semibold sm:col-span-2"
          >
            Tra cứu
          </button>
        </form>

        {/* 12-card grid */}
        <div className="mb-10 grid grid-cols-3 gap-2 sm:grid-cols-4 lg:grid-cols-6 lg:gap-3">
          {ZODIAC.map((z) => (
            <Link
              key={z.slug}
              href={`/12-con-giap?slug=${z.slug}&refYear=${refYear}`}
              className={`border-stroke-subtle bg-bg-elevated/40 hover:border-brand-gold/60 flex flex-col items-center gap-1 rounded-lg border p-3 text-center transition ${
                selected?.slug === z.slug ? "border-brand-gold bg-bg-elevated" : ""
              }`}
            >
              <div className="font-display text-ink-primary text-xl font-semibold">{z.name}</div>
              <div className="text-ink-muted text-[10px]">{z.english}</div>
              <div className="text-brand-gold/70 text-[10px]">{z.element}</div>
            </Link>
          ))}
        </div>

        {selected ? (
          <>
            <article className="border-stroke-subtle bg-bg-elevated/40 mb-6 rounded-2xl border p-6 lg:p-8">
              <div className="border-stroke-subtle border-b pb-4">
                <div className="text-brand-gold text-xs tracking-[0.2em] uppercase">
                  {selected.english} · {selected.element} · {selected.yinYang}
                </div>
                <h2 className="font-display text-ink-primary mt-1 text-3xl font-semibold lg:text-4xl">
                  Tuổi {selected.name}
                </h2>
                <p className="text-ink-secondary mt-3 text-base leading-relaxed">
                  {selected.description}
                </p>
              </div>

              <div className="mt-6 grid gap-6 lg:grid-cols-2">
                <Section title="Tính cách">
                  <p className="text-ink-secondary text-sm leading-relaxed">
                    {selected.traits.join(" · ")}
                  </p>
                </Section>

                <Section title="Tam Hợp">
                  <p className="text-ink-secondary text-sm">{selected.tamHop}</p>
                </Section>

                <Section title="Điểm mạnh">
                  <ul className="text-ink-secondary list-disc space-y-1 pl-5 text-sm">
                    {selected.strengths.map((s, i) => (
                      <li key={i}>{s}</li>
                    ))}
                  </ul>
                </Section>

                <Section title="Điểm yếu">
                  <ul className="text-ink-secondary list-disc space-y-1 pl-5 text-sm">
                    {selected.weaknesses.map((s, i) => (
                      <li key={i}>{s}</li>
                    ))}
                  </ul>
                </Section>

                <Section title="Sự nghiệp">
                  <p className="text-ink-secondary text-sm leading-relaxed">{selected.career}</p>
                </Section>

                <Section title="Tình yêu">
                  <p className="text-ink-secondary text-sm leading-relaxed">{selected.love}</p>
                </Section>
              </div>
            </article>

            {/* Vận năm */}
            {outlook ? (
              <article
                className={`mb-6 rounded-2xl border-2 p-6 lg:p-8 ${
                  outlook.category === "Tốt"
                    ? "border-emerald-500/40 bg-emerald-500/5"
                    : outlook.category === "Cần thận trọng"
                      ? "border-rose-500/40 bg-rose-500/5"
                      : "border-amber-500/40 bg-amber-500/5"
                }`}
              >
                <header className="border-stroke-subtle border-b pb-4">
                  <div className="text-brand-gold flex items-center gap-2 text-xs tracking-[0.2em] uppercase">
                    <Sparkles className="h-3.5 w-3.5" />
                    Vận năm {outlook.year} — Năm {outlook.yearAnimalName}
                  </div>
                  <div className="mt-3 flex items-baseline justify-between gap-3">
                    <h2
                      className={`font-display text-2xl font-bold lg:text-3xl ${
                        outlook.category === "Tốt"
                          ? "text-emerald-400"
                          : outlook.category === "Cần thận trọng"
                            ? "text-rose-400"
                            : "text-amber-400"
                      }`}
                    >
                      {outlook.category}
                    </h2>
                    <div className="text-brand-gold font-display text-3xl font-bold lg:text-4xl">
                      {outlook.relationScore}
                      <span className="text-ink-muted text-sm">/100</span>
                    </div>
                  </div>
                  <div className="mt-2 flex flex-wrap gap-2 text-xs">
                    <span className="border-stroke-subtle bg-bg-inset rounded-full border px-2.5 py-1">
                      {outlook.relation}
                    </span>
                    {outlook.isOwnYear ? (
                      <span className="rounded-full border border-amber-500/40 bg-amber-500/10 px-2.5 py-1 text-amber-300">
                        Năm tuổi (Bản Mệnh)
                      </span>
                    ) : null}
                    {outlook.tamTai.active ? (
                      <span
                        className={`rounded-full border px-2.5 py-1 ${
                          outlook.tamTai.position === 2
                            ? "border-rose-500/40 bg-rose-500/10 text-rose-300"
                            : "border-amber-500/40 bg-amber-500/10 text-amber-300"
                        }`}
                      >
                        {outlook.tamTai.label}
                      </span>
                    ) : null}
                  </div>
                  <p className="text-ink-secondary mt-3 text-sm leading-relaxed">{outlook.hint}</p>
                </header>

                <div className="mt-5 grid gap-3 lg:grid-cols-2">
                  <YearCard icon={<Briefcase className="h-4 w-4" />} title="Sự nghiệp">
                    {outlook.career}
                  </YearCard>
                  <YearCard icon={<Coins className="h-4 w-4" />} title="Tài chính">
                    {outlook.finance}
                  </YearCard>
                  <YearCard icon={<Heart className="h-4 w-4" />} title="Tình duyên">
                    {outlook.love}
                  </YearCard>
                  <YearCard icon={<Activity className="h-4 w-4" />} title="Sức khoẻ">
                    {outlook.health}
                  </YearCard>
                </div>

                <div className="mt-4 flex items-start gap-3 rounded-lg border border-amber-500/30 bg-amber-500/5 p-4">
                  <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-amber-400" />
                  <p className="text-ink-secondary text-xs leading-relaxed">{outlook.caution}</p>
                </div>
              </article>
            ) : null}

            {/* AI luận giải */}
            {outlook ? (
              <AiInsightPanel
                topic="horoscope"
                context={{
                  tool: "12-con-giap",
                  ownAnimal: selected.slug,
                  ownName: selected.name,
                  element: selected.element,
                  yinYang: selected.yinYang,
                  traits: selected.traits,
                  strengths: selected.strengths,
                  weaknesses: selected.weaknesses,
                  career: selected.career,
                  love: selected.love,
                  refYear: outlook.year,
                  yearAnimal: outlook.yearAnimalName,
                  relation: outlook.relation,
                  relationScore: outlook.relationScore,
                  isOwnYear: outlook.isOwnYear,
                  tamTai: outlook.tamTai,
                  category: outlook.category,
                  hint: outlook.hint,
                }}
                cta={`Hỏi "Thầy" về tuổi ${selected.name} năm ${outlook.year}`}
                title={`"Thầy" luận sâu tuổi ${selected.name} năm ${outlook.year}`}
                hint={`"Thầy" sẽ phân tích sâu vận năm ${outlook.year} cho người tuổi ${selected.name}: tháng nào nên hành động, hướng nào hợp, màu sắc / con số may mắn, và cách hoá giải hạn nếu có.`}
              />
            ) : null}
          </>
        ) : null}
      </div>
    </div>
  );
}

function Section({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <section>
      <h3 className="font-display text-brand-gold mb-2 text-sm font-semibold tracking-wider uppercase">
        {title}
      </h3>
      {children}
    </section>
  );
}

function YearCard({
  icon,
  title,
  children,
}: {
  icon: React.ReactNode;
  title: string;
  children: React.ReactNode;
}) {
  return (
    <div className="border-stroke-subtle/60 bg-bg-inset rounded-lg border p-4">
      <div className="text-brand-gold mb-2 flex items-center gap-2 text-xs font-semibold tracking-wider uppercase">
        {icon}
        {title}
      </div>
      <p className="text-ink-secondary text-xs leading-relaxed">{children}</p>
    </div>
  );
}
