import type { Metadata } from "next";
import { Sparkles, Users } from "lucide-react";
import { fateSummary, TOPIC_LABELS, type FateTopic } from "@/lib/extra-tools";
import { AiInsightPanel } from "@/components/ai/insight-panel";

export const metadata: Metadata = {
  title: "Sơ Mệnh 60 Hoa Giáp — Tử Vi Số",
  description:
    "Tra Mệnh nạp âm theo năm sinh, gợi ý sự nghiệp, tình duyên, gia đạo, sức khoẻ, tài lộc cùng tuổi hợp/kỵ.",
};

type Props = {
  searchParams: Promise<{
    year?: string;
    gender?: string;
    topic?: string;
  }>;
};

const TOPICS: FateTopic[] = ["career", "love", "family", "health", "finance"];

function isTopic(s: string | undefined): s is FateTopic {
  return !!s && (TOPICS as string[]).includes(s);
}

export default async function FateSummaryPage({ searchParams }: Props) {
  const sp = await searchParams;
  const year = sp.year ? parseInt(sp.year, 10) : null;
  const valid = year && year > 1900 && year < 2200;
  const gender = sp.gender === "Nam" || sp.gender === "Nữ" ? sp.gender : undefined;
  const topic = isTopic(sp.topic) ? sp.topic : undefined;

  const fate = valid ? fateSummary(year!, { gender, topic }) : null;

  return (
    <div className="bg-bg-base min-h-screen">
      <div className="mx-auto max-w-3xl 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">
            Sơ Mệnh 60 Hoa Giáp
          </h1>
          <p className="text-ink-secondary mt-2 text-sm">
            Mệnh nạp âm theo năm sinh — gợi ý theo 5 chủ đề + tuổi hợp / kỵ.
          </p>
        </div>

        <form
          method="GET"
          className="border-stroke-subtle bg-bg-elevated/40 mb-8 grid gap-3 rounded-xl border p-5 lg:grid-cols-3"
        >
          <div>
            <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={2200}
              required
              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">
              Giới tính <span className="text-ink-muted/60">(tuỳ chọn)</span>
            </label>
            <select
              name="gender"
              defaultValue={sp.gender ?? ""}
              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"
            >
              <option value="">— Không chọn —</option>
              <option value="Nam">Nam</option>
              <option value="Nữ">Nữ</option>
            </select>
          </div>
          <div>
            <label className="text-ink-muted block text-xs">
              Chủ đề <span className="text-ink-muted/60">(tuỳ chọn)</span>
            </label>
            <select
              name="topic"
              defaultValue={sp.topic ?? ""}
              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"
            >
              <option value="">— Tổng quát —</option>
              {TOPICS.map((t) => (
                <option key={t} value={t}>
                  {TOPIC_LABELS[t]}
                </option>
              ))}
            </select>
          </div>
          <div className="lg:col-span-3">
            <button
              type="submit"
              className="bg-brand-gold text-bg-base w-full rounded-md px-4 py-2.5 text-sm font-semibold"
            >
              Phân tích
            </button>
          </div>
        </form>

        {fate ? (
          <>
            <article className="border-stroke-subtle bg-bg-elevated/40 mb-6 rounded-2xl border p-6 lg:p-8">
              <header className="border-stroke-subtle border-b pb-4">
                <div className="text-brand-gold text-xs tracking-[0.2em] uppercase">
                  Năm {fate.year} · {fate.element}
                </div>
                <h2 className="font-display text-ink-primary mt-1 text-3xl font-semibold lg:text-4xl">
                  {fate.stem} {fate.branch}
                </h2>
                <div className="text-brand-gold mt-2 font-medium">{fate.napAm}</div>
              </header>
              <p className="text-ink-secondary mt-4 text-base leading-relaxed">
                {fate.description}
              </p>
            </article>

            {fate.topic ? (
              <article className="mb-6 rounded-2xl border border-amber-500/30 bg-amber-500/5 p-6 lg:p-8">
                <div className="flex items-center gap-2 text-xs tracking-[0.2em] text-amber-300 uppercase">
                  <Sparkles className="h-3.5 w-3.5" />
                  Gợi ý {fate.topic.label.toLowerCase()} cho mệnh {fate.element}
                </div>
                <ul className="mt-4 space-y-3">
                  {fate.topic.tips.map((tip, i) => (
                    <li key={i} className="text-ink-secondary flex gap-2 text-sm leading-relaxed">
                      <span className="shrink-0 text-amber-400">·</span>
                      {tip}
                    </li>
                  ))}
                </ul>
              </article>
            ) : (
              <article className="border-stroke-subtle bg-bg-inset/40 mb-6 rounded-xl border border-dashed p-5 text-center">
                <p className="text-ink-muted text-xs">
                  Chọn chủ đề (Sự nghiệp / Tình duyên / Gia đạo / Sức khoẻ / Tài lộc) trong form để
                  xem gợi ý chi tiết.
                </p>
              </article>
            )}

            {fate.zodiac ? (
              <article className="border-stroke-subtle bg-bg-elevated/40 mb-6 rounded-2xl border p-6 lg:p-8">
                <div className="text-brand-gold flex items-center gap-2 text-xs tracking-[0.2em] uppercase">
                  <Users className="h-3.5 w-3.5" />
                  Tuổi hợp / Tuổi kỵ ({fate.zodiac.gender})
                </div>
                <div className="mt-4 grid gap-4 lg:grid-cols-2">
                  <div className="rounded-lg border border-emerald-500/30 bg-emerald-500/5 p-4">
                    <div className="text-[11px] tracking-wider text-emerald-300 uppercase">
                      Tam hợp (hỗ trợ)
                    </div>
                    <div className="mt-2 flex flex-wrap gap-1.5">
                      {fate.zodiac.tamHop.map((b) => (
                        <span
                          key={b}
                          className="rounded border border-emerald-500/40 bg-emerald-500/10 px-2 py-0.5 text-sm font-medium text-emerald-300"
                        >
                          {b}
                        </span>
                      ))}
                    </div>
                    <p className="text-ink-secondary mt-3 text-xs leading-relaxed">
                      Cùng nhóm Tam hợp với {fate.zodiac.branch} — phối hợp làm ăn, kết hôn, hợp tác
                      lâu dài đều thuận lợi.
                    </p>
                  </div>
                  <div className="rounded-lg border border-rose-500/30 bg-rose-500/5 p-4">
                    <div className="text-[11px] tracking-wider text-rose-300 uppercase">
                      Tứ hành xung (kỵ)
                    </div>
                    <div className="mt-2 flex flex-wrap gap-1.5">
                      {fate.zodiac.tuHanhXung.map((b) => (
                        <span
                          key={b}
                          className="rounded border border-rose-500/40 bg-rose-500/10 px-2 py-0.5 text-sm font-medium text-rose-300"
                        >
                          {b}
                        </span>
                      ))}
                    </div>
                    <p className="text-ink-secondary mt-3 text-xs leading-relaxed">
                      Đối xung 180° với {fate.zodiac.branch} — cần cẩn trọng khi hợp tác hoặc kết
                      hôn, dễ phát sinh xung khắc.
                    </p>
                  </div>
                </div>
              </article>
            ) : (
              <article className="border-stroke-subtle bg-bg-inset/40 mb-6 rounded-xl border border-dashed p-5 text-center">
                <p className="text-ink-muted text-xs">
                  Chọn giới tính để xem tuổi hợp (Tam hợp) và tuổi kỵ (Tứ hành xung).
                </p>
              </article>
            )}

            <AiInsightPanel
              topic="numerology"
              context={{
                tool: "fate-summary-60",
                year: fate.year,
                stem: fate.stem,
                branch: fate.branch,
                napAm: fate.napAm,
                element: fate.element,
                description: fate.description,
                topic: fate.topic?.label,
                gender,
                tamHop: fate.zodiac?.tamHop,
                tuHanhXung: fate.zodiac?.tuHanhXung,
              }}
              cta={'Hỏi "Thầy"'}
              title="Luận giải mệnh nạp âm chuyên sâu"
              hint='"Thầy" sẽ tổng hợp Mệnh nạp âm + Can-Chi + chủ đề bạn chọn + tuổi hợp/kỵ thành đoạn luận giải sâu hơn, đề xuất hướng phát triển và lưu ý.'
            />
          </>
        ) : null}
      </div>
    </div>
  );
}
