import type { Metadata } from "next";
import Link from "next/link";
import { ZODIAC, zodiacBySlug, zodiacFromYear } from "@/lib/zodiac";
import { yearlyHoroscope } from "@/lib/horoscope";
import { AiInsightPanel } from "@/components/ai/insight-panel";

export const metadata: Metadata = {
  title: "Tử Vi Năm — Tử Vi Số",
  description: "Tử vi 12 con giáp theo năm — sự nghiệp, tình yêu, tài lộc, sức khoẻ.",
};

const MONTH_NAMES = ["", "T1", "T2", "T3", "T4", "T5", "T6", "T7", "T8", "T9", "T10", "T11", "T12"];

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

export default async function TuViNamPage({ searchParams }: Props) {
  const sp = await searchParams;
  const targetYear = sp.year ? parseInt(sp.year, 10) : new Date().getFullYear();

  let selected = sp.slug ? zodiacBySlug(sp.slug) : null;
  if (!selected && sp.birthYear) {
    const y = parseInt(sp.birthYear, 10);
    if (y > 1900 && y < 2200) selected = zodiacFromYear(y);
  }

  const horo = selected ? yearlyHoroscope(selected.slug, targetYear) : null;

  return (
    <div className="bg-bg-base min-h-screen">
      <div className="mx-auto max-w-4xl px-4 py-8 lg:py-12">
        <div className="mb-6 text-center">
          <h1 className="font-display text-ink-primary text-3xl font-semibold lg:text-4xl">
            Tử Vi Năm {targetYear}
          </h1>
          <p className="text-ink-secondary mt-2 text-sm">
            Sự nghiệp, tình yêu, tài lộc, sức khoẻ theo 12 con giáp.
          </p>
        </div>

        <form
          method="GET"
          className="border-stroke-subtle bg-bg-elevated/40 mx-auto mb-6 grid max-w-2xl gap-3 rounded-xl border p-4 lg:grid-cols-3"
        >
          <div>
            <label className="text-ink-muted block text-xs">Năm xem</label>
            <input
              type="number"
              name="year"
              defaultValue={targetYear}
              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>
          <div>
            <label className="text-ink-muted block text-xs">Năm sinh</label>
            <input
              type="number"
              name="birthYear"
              defaultValue={sp.birthYear ?? ""}
              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>
          <button
            type="submit"
            className="bg-brand-gold text-bg-base self-end rounded-md px-4 py-2 text-sm font-semibold"
          >
            Xem
          </button>
        </form>

        <div className="mb-6 grid grid-cols-3 gap-2 sm:grid-cols-6 lg:grid-cols-12 lg:gap-2">
          {ZODIAC.map((z) => (
            <Link
              key={z.slug}
              href={`/tu-vi-nam?slug=${z.slug}&year=${targetYear}`}
              className={`border-stroke-subtle bg-bg-elevated/40 hover:border-brand-gold/60 flex flex-col items-center rounded-md border p-2 text-center transition ${
                selected?.slug === z.slug ? "border-brand-gold bg-bg-elevated" : ""
              }`}
            >
              <div className="font-display text-ink-primary text-sm font-semibold">{z.name}</div>
            </Link>
          ))}
        </div>

        {horo ? (
          <article className="border-stroke-subtle bg-bg-elevated/40 rounded-2xl border p-6 lg:p-8">
            <header className="border-stroke-subtle border-b pb-4">
              <div className="flex items-baseline justify-between">
                <div>
                  <div className="text-brand-gold text-xs tracking-[0.2em] uppercase">
                    Tuổi {horo.zodiac.name} · Năm {horo.year}
                  </div>
                  <h2 className="font-display text-ink-primary mt-1 text-2xl font-semibold lg:text-3xl">
                    Tử vi năm {horo.year}
                  </h2>
                </div>
                <div className="font-display text-brand-gold text-5xl font-bold lg:text-6xl">
                  {horo.scoreOverall}
                  <span className="text-ink-muted text-base">/100</span>
                </div>
              </div>
              <p className="text-ink-secondary mt-3 text-sm leading-relaxed">{horo.summary}</p>
            </header>

            <div className="mt-6 grid gap-4 lg:grid-cols-2">
              <Section title="Sự nghiệp">{horo.career}</Section>
              <Section title="Tình yêu / Hôn nhân">{horo.love}</Section>
              <Section title="Tài lộc">{horo.wealth}</Section>
              <Section title="Sức khoẻ">{horo.health}</Section>
            </div>

            <div className="mt-6 grid gap-4 lg:grid-cols-2">
              <div className="border-stroke-subtle/60 rounded-lg border bg-emerald-500/5 p-4">
                <h3 className="mb-2 text-xs font-semibold tracking-wider text-emerald-400 uppercase">
                  Tháng tốt
                </h3>
                <div className="flex flex-wrap gap-2">
                  {horo.bestMonths.map((m) => (
                    <span
                      key={m}
                      className="rounded-full bg-emerald-500/15 px-3 py-1 text-xs font-medium text-emerald-300"
                    >
                      {MONTH_NAMES[m]}
                    </span>
                  ))}
                </div>
              </div>
              <div className="border-stroke-subtle/60 bg-brand-red/5 rounded-lg border p-4">
                <h3 className="text-brand-red mb-2 text-xs font-semibold tracking-wider uppercase">
                  Tháng xấu
                </h3>
                <div className="flex flex-wrap gap-2">
                  {horo.worstMonths.map((m) => (
                    <span
                      key={m}
                      className="bg-brand-red/15 text-brand-red rounded-full px-3 py-1 text-xs font-medium"
                    >
                      {MONTH_NAMES[m]}
                    </span>
                  ))}
                </div>
              </div>
            </div>
          </article>
        ) : (
          <p className="text-ink-muted text-center text-sm">Chọn tuổi hoặc nhập năm sinh.</p>
        )}

        {horo ? (
          <AiInsightPanel
            topic="horoscope"
            context={{
              kind: "yearly",
              year: horo.year,
              zodiac: horo.zodiac.name,
              element: horo.zodiac.element,
              scoreOverall: horo.scoreOverall,
              summary: horo.summary,
              career: horo.career,
              love: horo.love,
              wealth: horo.wealth,
              health: horo.health,
              bestMonths: horo.bestMonths,
              worstMonths: horo.worstMonths,
            }}
            cta={'Hỏi "Thầy" luận sâu cả năm'}
            title="Luận sâu tử vi năm"
            hint='"Thầy" sẽ phân tích chi tiết hơn từng giai đoạn trong năm và gợi ý chiến lược tổng thể.'
          />
        ) : null}
      </div>
    </div>
  );
}

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