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

export const metadata: Metadata = {
  title: "Tử Vi Hôm Nay — Tử Vi Số",
  description: "Tử vi hằng ngày cho 12 con giáp.",
};

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

export default async function TuViNgayPage({ searchParams }: Props) {
  const sp = await searchParams;
  const dateISO = sp.date || new Date().toISOString().slice(0, 10);

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

  const horo = selected ? dailyHoroscope(selected.slug, dateISO) : null;
  const dateLabel = new Date(dateISO + "T00:00:00").toLocaleDateString("vi-VN", {
    weekday: "long",
    year: "numeric",
    month: "long",
    day: "numeric",
  });

  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 Hôm Nay
          </h1>
          <p className="text-ink-secondary mt-2 text-sm">{dateLabel}</p>
        </div>

        <form
          method="GET"
          className="border-stroke-subtle bg-bg-elevated/40 mx-auto mb-6 flex max-w-md items-end gap-2 rounded-xl border p-4"
        >
          <input type="hidden" name="date" value={dateISO} />
          <div className="flex-1">
            <label className="text-ink-muted block text-xs">Năm sinh dương lịch</label>
            <input
              type="number"
              name="year"
              defaultValue={sp.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>
          <button
            type="submit"
            className="bg-brand-gold text-bg-base 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-ngay?slug=${z.slug}&date=${dateISO}`}
              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} · {horo.zodiac.element}
                  </div>
                  <h2 className="font-display text-ink-primary mt-1 text-2xl font-semibold lg:text-3xl">
                    {horo.zodiac.name} hôm nay
                  </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.overall}</p>
              <div className="mt-3 flex flex-wrap gap-3 text-xs">
                <span className="border-stroke-subtle bg-bg-inset rounded-full border px-3 py-1">
                  Màu may mắn: <span className="text-brand-gold">{horo.luckyColor}</span>
                </span>
                <span className="border-stroke-subtle bg-bg-inset rounded-full border px-3 py-1">
                  Số may mắn: <span className="text-brand-gold">{horo.luckyNumber}</span>
                </span>
              </div>
            </header>

            <div className="mt-6 grid gap-4 lg:grid-cols-3">
              <Section title="Sự nghiệp">{horo.career}</Section>
              <Section title="Tình yêu">{horo.love}</Section>
              <Section title="Sức khoẻ">{horo.health}</Section>
            </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: "daily",
              date: dateISO,
              zodiac: horo.zodiac.name,
              element: horo.zodiac.element,
              scoreOverall: horo.scoreOverall,
              luckyColor: horo.luckyColor,
              luckyNumber: horo.luckyNumber,
              overall: horo.overall,
              career: horo.career,
              love: horo.love,
              health: horo.health,
            }}
            cta={'Hỏi "Thầy" luận chi tiết hơn'}
            title="Luận sâu tử vi ngày"
            hint='Phần trên là tóm tắt nhanh. "Thầy" sẽ mở rộng phân tích và gợi ý 2-3 việc nên làm hôm nay.'
          />
        ) : 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>
  );
}
