import type { Metadata } from "next";
import {
  computeBatTu,
  fiveElementsCount,
  dayMaster,
  computeDungThan,
  type Pillar,
} from "@/lib/bat-tu";
import { Sparkles, Compass, Palette, Hash, Briefcase } from "lucide-react";
import { AiInsightPanel } from "@/components/ai/insight-panel";
import { DateInput } from "@/components/ui/date-input";

export const metadata: Metadata = {
  title: "Tứ Trụ – Bát Tự — Tử Vi Số",
  description: "Lập 4 trụ năm-tháng-ngày-giờ và phân tích ngũ hành Bát Tự.",
};

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

export default async function BatTuPage({ searchParams }: Props) {
  const sp = await searchParams;
  const date = sp.date ?? "";
  const hour = sp.hour ? parseInt(sp.hour, 10) : null;
  const d = date ? new Date(date) : null;
  const valid = d && !isNaN(d.getTime()) && hour !== null && hour >= 0 && hour <= 23;
  const bt = valid ? computeBatTu(d!.getFullYear(), d!.getMonth() + 1, d!.getDate(), hour!) : null;
  const counts = bt ? fiveElementsCount(bt) : null;
  const master = bt ? dayMaster(bt) : null;
  const dungThan = bt ? computeDungThan(bt) : null;
  const total = counts ? Object.values(counts).reduce((s, n) => s + n, 0) : 0;

  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-8 text-center">
          <h1 className="font-display text-ink-primary text-3xl font-semibold lg:text-4xl">
            Tứ Trụ – Bát Tự
          </h1>
          <p className="text-ink-secondary mt-2 text-sm">
            Lập 4 trụ năm-tháng-ngày-giờ và phân tích ngũ hành Bát Tự.
          </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 className="lg:col-span-2">
            <label className="text-ink-muted block text-xs">Ngày sinh dương lịch</label>
            <div className="mt-1">
              <DateInput name="date" defaultValue={date} required />
            </div>
          </div>
          <div>
            <label className="text-ink-muted block text-xs">Giờ sinh (0–23)</label>
            <input
              type="number"
              name="hour"
              defaultValue={sp.hour ?? ""}
              min={0}
              max={23}
              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>
          <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"
          >
            Lập Bát Tự
          </button>
        </form>

        {bt && counts && master ? (
          <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="text-brand-gold text-xs tracking-[0.2em] uppercase">
                Nhật chủ · {master.element} {master.yinYang}
              </div>
              <h2 className="font-display text-ink-primary mt-1 text-3xl font-semibold lg:text-4xl">
                {master.stem}
              </h2>
              <p className="text-ink-secondary mt-2 text-sm leading-relaxed">
                Nhật-can là gốc của Bát Tự. Mọi cát hung trong lá số đều quy về sự cân bằng ngũ hành
                xung quanh nhật-can.
              </p>
            </header>

            <div className="mt-6 grid grid-cols-2 gap-3 lg:grid-cols-4">
              <PillarCard label="Trụ Năm (Niên)" pillar={bt.year} />
              <PillarCard label="Trụ Tháng (Nguyệt)" pillar={bt.month} />
              <PillarCard label="Trụ Ngày (Nhật)" pillar={bt.day} highlight />
              <PillarCard label="Trụ Giờ (Thời)" pillar={bt.hour} />
            </div>

            <div className="mt-8">
              <h3 className="font-display text-brand-gold mb-3 text-sm font-semibold tracking-wider uppercase">
                Ngũ hành tổng quan ({total} đơn vị)
              </h3>
              <div className="space-y-2">
                {Object.entries(counts).map(([el, n]) => (
                  <div key={el} className="flex items-center gap-3">
                    <span className="text-ink-secondary w-16 text-sm">{el}</span>
                    <div className="bg-bg-overlay/50 h-3 flex-1 overflow-hidden rounded-full">
                      <div
                        className="bg-brand-gold h-full"
                        style={{ width: `${(n / total) * 100}%` }}
                      />
                    </div>
                    <span className="text-ink-secondary w-8 text-right font-mono text-xs">{n}</span>
                  </div>
                ))}
              </div>
              <p className="text-ink-muted mt-3 text-xs leading-relaxed">
                Cân bằng tốt khi mỗi hành có 1-2 đơn vị. Hành thiếu (0) cần bổ sung qua màu sắc, vật
                phẩm, hướng nhà; hành quá vượng (≥4) cần tiết khí.
              </p>
            </div>
          </article>
        ) : null}

        {dungThan ? (
          <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 flex items-center gap-2 text-xs tracking-[0.2em] uppercase">
                <Sparkles className="h-3.5 w-3.5" />
                Dụng thần · ngũ hành cần bổ sung
              </div>
              <div className="mt-2 flex items-baseline gap-3">
                <h2
                  className={`font-display text-2xl font-semibold lg:text-3xl ${
                    dungThan.selfStrength === "vượng"
                      ? "text-amber-400"
                      : dungThan.selfStrength === "nhược"
                        ? "text-rose-400"
                        : "text-emerald-400"
                  }`}
                >
                  Nhật chủ {dungThan.selfStrength}
                </h2>
                <span className="text-ink-muted font-mono text-sm">
                  {dungThan.selfScore}/{dungThan.totalElements}
                </span>
              </div>
              <p className="text-ink-secondary mt-3 text-sm leading-relaxed">{dungThan.summary}</p>
            </header>

            <div className="mt-5 grid gap-3 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">
                  Hành cần bổ sung (dụng thần)
                </div>
                <div className="mt-2 flex flex-wrap gap-1.5">
                  {dungThan.needs.map((el) => (
                    <span
                      key={el}
                      className="rounded border border-emerald-500/40 bg-emerald-500/10 px-3 py-1 text-base font-semibold text-emerald-300"
                    >
                      {el}
                    </span>
                  ))}
                </div>
              </div>
              {dungThan.avoids.length > 0 ? (
                <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">
                    Hành nên tránh (kỵ thần)
                  </div>
                  <div className="mt-2 flex flex-wrap gap-1.5">
                    {dungThan.avoids.map((el) => (
                      <span
                        key={el}
                        className="rounded border border-rose-500/40 bg-rose-500/10 px-3 py-1 text-base font-semibold text-rose-300"
                      >
                        {el}
                      </span>
                    ))}
                  </div>
                </div>
              ) : (
                <div className="border-stroke-subtle/60 bg-bg-inset rounded-lg border p-4">
                  <div className="text-ink-muted text-[11px] tracking-wider uppercase">
                    Hành nên tránh
                  </div>
                  <p className="text-ink-muted mt-2 text-xs">
                    Bát Tự cân bằng — không có hành rõ rệt cần tránh.
                  </p>
                </div>
              )}
            </div>

            <div className="mt-5 grid gap-3 lg:grid-cols-2">
              <DungThanCard
                icon={<Compass className="h-4 w-4" />}
                label="Hướng tốt"
                items={dungThan.directions}
              />
              <DungThanCard
                icon={<Palette className="h-4 w-4" />}
                label="Màu sắc hợp"
                items={dungThan.colors}
              />
              <DungThanCard
                icon={<Hash className="h-4 w-4" />}
                label="Số may mắn"
                items={dungThan.numbers.map(String)}
              />
              <DungThanCard
                icon={<Briefcase className="h-4 w-4" />}
                label="Ngành nghề phù hợp"
                items={dungThan.careers}
              />
            </div>
          </article>
        ) : null}

        {bt && counts && master ? (
          <AiInsightPanel
            topic="bat-tu"
            context={{
              pillars: {
                year: `${bt.year.stem}${bt.year.branch}`,
                month: `${bt.month.stem}${bt.month.branch}`,
                day: `${bt.day.stem}${bt.day.branch}`,
                hour: `${bt.hour.stem}${bt.hour.branch}`,
              },
              dayMaster: `${master.stem} (${master.element} ${master.yinYang})`,
              fiveElements: counts,
              selfStrength: dungThan?.selfStrength,
              dungThan: dungThan?.needs,
              kyThan: dungThan?.avoids,
              luckyDirections: dungThan?.directions,
              luckyColors: dungThan?.colors,
              luckyNumbers: dungThan?.numbers,
              suggestedCareers: dungThan?.careers,
              date,
              hour,
            }}
            cta={'Hỏi "Thầy" luận sâu Bát Tự'}
            title="Luận sâu Bát Tự + Dụng thần"
            hint='Phần trên là tính 4 trụ + đếm ngũ hành + xác định dụng thần. "Thầy" sẽ tổng hợp và đưa ra lời khuyên cụ thể về điều chỉnh phong thuỷ và lựa chọn nghề.'
          />
        ) : null}
      </div>
    </div>
  );
}

function PillarCard({
  label,
  pillar,
  highlight,
}: {
  label: string;
  pillar: Pillar;
  highlight?: boolean;
}) {
  return (
    <div
      className={`border-stroke-subtle/60 rounded-lg border p-4 text-center ${
        highlight ? "border-brand-gold bg-bg-overlay/40" : "bg-bg-inset"
      }`}
    >
      <div className="text-ink-muted text-[10px] tracking-wider uppercase">{label}</div>
      <div className="font-display text-ink-primary mt-2 text-2xl font-semibold">{pillar.stem}</div>
      <div className="font-display text-brand-gold text-2xl font-semibold">{pillar.branch}</div>
      <div className="text-ink-muted mt-2 text-[10px]">
        {pillar.element} · {pillar.yinYang}
      </div>
      {pillar.hourRange ? (
        <div className="text-ink-muted mt-1 text-[10px]">{pillar.hourRange}</div>
      ) : null}
    </div>
  );
}

function DungThanCard({
  icon,
  label,
  items,
}: {
  icon: React.ReactNode;
  label: string;
  items: string[];
}) {
  return (
    <div className="border-stroke-subtle/60 bg-bg-inset rounded-lg border p-4">
      <div className="text-brand-gold flex items-center gap-1.5 text-[11px] tracking-wider uppercase">
        {icon}
        {label}
      </div>
      <div className="mt-2 flex flex-wrap gap-1.5">
        {items.map((item) => (
          <span
            key={item}
            className="border-stroke-default bg-bg-overlay/60 text-ink-secondary rounded border px-2 py-0.5 text-xs"
          >
            {item}
          </span>
        ))}
      </div>
    </div>
  );
}
