import type { Metadata } from "next";
import Link from "next/link";
import { Calendar, Compass, Home as HomeIcon, Sparkles } from "lucide-react";
import {
  isKimLau,
  isHoangOc,
  isTamTai,
  batTrach,
  previewBuildYears,
  findGoodBuildYears,
  buildMaterialAdvice,
} from "@/lib/feng-shui/year-pick";
import { AiInsightPanel } from "@/components/ai/insight-panel";

export const metadata: Metadata = {
  title: "Năm Tốt Xây Nhà — Tử Vi Số",
  description:
    "Kiểm tra năm tốt xây nhà theo Kim Lâu, Hoang Ốc, Tam Tai — gợi ý hướng nhà, vật liệu phù hợp mệnh gia chủ và 5 năm tốt kế tiếp.",
};

type Props = {
  searchParams: Promise<{ birth?: string; build?: string; gender?: string }>;
};

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

  const kl = valid ? isKimLau(birth!, build!) : null;
  const ho = valid ? isHoangOc(birth!, build!) : null;
  const tt = valid ? isTamTai(birth!, build!) : null;

  const allOk = kl?.ok && ho?.ok && tt?.ok;
  const anyBad = kl && ho && tt && (!kl.ok || !ho.ok || !tt.ok);

  // Personalization: only when birth is valid
  const trach = birth && gender ? batTrach(birth, gender) : null;
  const materials = birth ? buildMaterialAdvice(birth) : null;
  const goodYears = birth && build ? findGoodBuildYears(birth, build, 5, 30) : null;
  const preview = birth && build ? previewBuildYears(birth, build, 10) : 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">
            Năm Tốt Xây Nhà
          </h1>
          <p className="text-ink-secondary mt-2 text-sm">
            3 yếu tố Kim Lâu / Hoang Ốc / Tam Tai + hướng nhà Bát Trạch + vật liệu hợp mệnh.
          </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 gia chủ</label>
            <input
              type="number"
              name="birth"
              defaultValue={sp.birth ?? ""}
              placeholder="vd: 1985"
              min={1900}
              max={2100}
              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">Năm dự kiến xây</label>
            <input
              type="number"
              name="build"
              defaultValue={sp.build ?? ""}
              placeholder="vd: 2026"
              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>
          <button
            type="submit"
            className="bg-brand-gold text-bg-base rounded-md px-4 py-2.5 text-sm font-semibold lg:col-span-3"
          >
            Kiểm tra
          </button>
        </form>

        {valid && kl && ho && tt ? (
          <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="flex items-baseline justify-between">
                <div>
                  <div className="text-brand-gold text-xs tracking-[0.2em] uppercase">
                    Tuổi mụ {kl.ageMu} — Năm {build}
                  </div>
                  <h2
                    className={`font-display mt-1 text-3xl font-semibold lg:text-4xl ${
                      allOk ? "text-emerald-400" : "text-brand-red"
                    }`}
                  >
                    {allOk ? "Năm tốt — không phạm kỵ" : "Năm có yếu tố không lý tưởng"}
                  </h2>
                </div>
              </div>
              {anyBad ? (
                <p className="text-ink-secondary mt-3 text-sm leading-relaxed">
                  Có thể giải bằng cách mượn tuổi (mượn người không phạm cả 3 yếu tố để đứng tên
                  khởi công), hoặc dời sang năm khác — xem &ldquo;5 năm tốt kế tiếp&rdquo; bên dưới.
                </p>
              ) : (
                <p className="text-ink-secondary mt-3 text-sm leading-relaxed">
                  Cả 3 yếu tố Kim Lâu, Hoang Ốc, Tam Tai đều thuận. Có thể tiến hành xây dựng, chú ý
                  chọn ngày khởi công cụ thể —{" "}
                  <Link href="/xem-ngay-tot" className="text-brand-gold underline">
                    xem ngày tốt
                  </Link>
                  .
                </p>
              )}
            </header>

            <div className="mt-6 space-y-3">
              <Factor
                label="Kim Lâu"
                ok={kl.ok}
                detail={kl.ok ? "Không phạm Kim Lâu." : `Phạm ${kl.type}.`}
              />
              <Factor
                label="Hoang Ốc"
                ok={ho.ok}
                detail={`${ho.type} — ${ho.ok ? "tốt" : "không tốt"}.`}
              />
              <Factor
                label="Tam Tai"
                ok={tt.ok}
                detail={
                  tt.ok
                    ? "Không phạm Tam Tai."
                    : `Phạm Tam Tai (nhóm ${tt.triad}). Trong 3 năm Tam Tai nên hạn chế việc lớn.`
                }
              />
            </div>
          </article>
        ) : null}

        {trach ? (
          <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">
              <Compass className="h-3.5 w-3.5" />
              Hướng nhà theo Bát Trạch
            </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">
                  Cung mệnh
                </div>
                <div className="font-display mt-1 text-2xl font-semibold text-emerald-400">
                  {trach.cung}
                </div>
                <div className="text-ink-secondary mt-1 text-xs">{trach.group}</div>
                <div className="mt-3">
                  <div className="text-[11px] tracking-wider text-emerald-300 uppercase">
                    4 hướng tốt
                  </div>
                  <div className="mt-1.5 flex flex-wrap gap-1.5">
                    {trach.goodDirections.map((d) => (
                      <span
                        key={d}
                        className="rounded border border-emerald-500/40 bg-emerald-500/10 px-2 py-0.5 text-xs font-medium text-emerald-300"
                      >
                        {d}
                      </span>
                    ))}
                  </div>
                </div>
              </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">
                  4 hướng cần tránh
                </div>
                <div className="mt-2 flex flex-wrap gap-1.5">
                  {trach.badDirections.map((d) => (
                    <span
                      key={d}
                      className="rounded border border-rose-500/40 bg-rose-500/10 px-2 py-0.5 text-xs font-medium text-rose-300"
                    >
                      {d}
                    </span>
                  ))}
                </div>
                <p className="text-ink-secondary mt-3 text-xs leading-relaxed">
                  Tránh đặt cửa chính, bếp, phòng ngủ chính ở các hướng này. Nếu nhà đã sẵn ở hướng
                  xấu, bố trí phụ kiện bài trí để hoá giải.
                </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 hướng nhà và 4 hướng cần tránh theo Bát Trạch.
            </p>
          </article>
        )}

        {materials ? (
          <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">
              <HomeIcon className="h-3.5 w-3.5" />
              Vật liệu &amp; phòng ốc theo Mệnh {materials.element}
            </div>
            <div className="mt-4 grid gap-3 lg:grid-cols-2">
              <div className="border-stroke-subtle/60 bg-bg-inset rounded-lg border p-4">
                <div className="text-[11px] tracking-wider text-emerald-300 uppercase">
                  Vật liệu hợp
                </div>
                <ul className="mt-2 space-y-1 text-xs">
                  {materials.good.map((m) => (
                    <li key={m} className="text-ink-secondary flex gap-2">
                      <span className="shrink-0 text-emerald-400">·</span>
                      {m}
                    </li>
                  ))}
                </ul>
              </div>
              <div className="border-stroke-subtle/60 bg-bg-inset rounded-lg border p-4">
                <div className="text-[11px] tracking-wider text-rose-300 uppercase">
                  Vật liệu nên tránh
                </div>
                <ul className="mt-2 space-y-1 text-xs">
                  {materials.avoid.map((m) => (
                    <li key={m} className="text-ink-secondary flex gap-2">
                      <span className="shrink-0 text-rose-400">·</span>
                      {m}
                    </li>
                  ))}
                </ul>
              </div>
              <div className="border-stroke-subtle/60 bg-bg-inset rounded-lg border p-4 lg:col-span-2">
                <div className="text-brand-gold text-[11px] tracking-wider uppercase">
                  Bố trí phòng ốc
                </div>
                <ul className="mt-2 space-y-1 text-xs">
                  {materials.rooms.map((r) => (
                    <li key={r} className="text-ink-secondary flex gap-2">
                      <span className="text-brand-gold shrink-0">·</span>
                      {r}
                    </li>
                  ))}
                </ul>
              </div>
            </div>
          </article>
        ) : null}

        {goodYears && goodYears.length > 0 ? (
          <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">
              <Calendar className="h-3.5 w-3.5" />5 năm tốt kế tiếp
            </div>
            <div className="mt-4 grid gap-2">
              {goodYears.map((y) => (
                <div
                  key={y.year}
                  className="flex items-baseline justify-between rounded-lg border border-emerald-500/30 bg-emerald-500/5 px-4 py-3"
                >
                  <div>
                    <span className="font-display text-xl font-semibold text-emerald-300">
                      {y.year}
                    </span>
                    <span className="text-ink-muted ml-2 text-xs">
                      tuổi mụ {y.ageMu} · {y.hoangOcType}
                    </span>
                  </div>
                  <span className="text-xs text-emerald-300">✓ tốt cả 3 yếu tố</span>
                </div>
              ))}
            </div>
          </article>
        ) : null}

        {preview ? (
          <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">
              <Calendar className="h-3.5 w-3.5" />
              Lịch 10 năm tới (kể từ {build})
            </div>
            <div className="mt-4 grid grid-cols-2 gap-2 lg:grid-cols-5">
              {preview.map((y) => (
                <div
                  key={y.year}
                  className={`rounded-lg border p-3 text-center ${
                    y.ok
                      ? "border-emerald-500/30 bg-emerald-500/5"
                      : "border-rose-500/30 bg-rose-500/5"
                  }`}
                >
                  <div
                    className={`font-display text-xl font-semibold ${
                      y.ok ? "text-emerald-300" : "text-rose-300"
                    }`}
                  >
                    {y.year}
                  </div>
                  <div className="text-ink-muted mt-0.5 text-[11px]">tuổi mụ {y.ageMu}</div>
                  <div
                    className={`mt-1 text-[11px] ${y.ok ? "text-emerald-400" : "text-rose-400"}`}
                  >
                    {y.ok ? "✓ tốt" : "✗ kỵ"}
                  </div>
                  {y.reasons.length > 0 ? (
                    <div className="text-ink-muted mt-1 text-[10px] leading-tight">
                      {y.reasons.join("; ")}
                    </div>
                  ) : null}
                </div>
              ))}
            </div>
          </article>
        ) : null}

        {valid && kl && ho && tt ? (
          <AiInsightPanel
            topic="numerology"
            context={{
              tool: "build-year",
              birthYear: birth,
              buildYear: build,
              gender,
              kimLau: kl.ok ? "không phạm" : kl.type,
              hoangOc: ho.type,
              tamTai: tt.ok ? "không phạm" : `phạm (${tt.triad})`,
              cung: trach?.cung,
              group: trach?.group,
              goodDirections: trach?.goodDirections,
              element: materials?.element,
              goodMaterials: materials?.good,
              nextGoodYears: goodYears?.map((y) => y.year),
            }}
            cta={'Hỏi "Thầy"'}
            title="Luận giải chi tiết và kế hoạch xây dựng"
            hint='"Thầy" sẽ tổng hợp 3 yếu tố + hướng Bát Trạch + vật liệu hợp mệnh + lịch 10 năm để đưa ra chiến lược xây dựng tối ưu cho bạn.'
          />
        ) : null}
      </div>
    </div>
  );
}

function Factor({ label, ok, detail }: { label: string; ok: boolean; detail: string }) {
  return (
    <div
      className={`border-stroke-subtle/60 flex items-start gap-3 rounded-lg border p-4 ${
        ok ? "bg-emerald-500/5" : "bg-brand-red/5"
      }`}
    >
      <div
        className={`flex h-8 w-8 shrink-0 items-center justify-center rounded-full font-bold ${
          ok ? "bg-emerald-500/20 text-emerald-400" : "bg-brand-red/20 text-brand-red"
        }`}
      >
        {ok ? "✓" : "✗"}
      </div>
      <div className="min-w-0 flex-1">
        <div className="text-ink-primary text-sm font-medium">{label}</div>
        <div className="text-ink-secondary mt-0.5 text-xs leading-relaxed">{detail}</div>
      </div>
    </div>
  );
}
