import type { Metadata } from "next";
import { Briefcase, ChevronDown } from "lucide-react";
import { deepCompat } from "@/lib/compat-deep";
import { AiInsightPanel } from "@/components/ai/insight-panel";
import { DateInput } from "@/components/ui/date-input";

export const metadata: Metadata = {
  title: "Hợp Tuổi Làm Ăn — Phân Tích Đa Phương Pháp — Tử Vi Số",
  description:
    "Hợp tuổi đối tác kinh doanh — phân tích chuyên sâu 4 phương pháp (Tử Vi nặng Mệnh + Cung Phi, Cung Hoàng Đạo, Bát Tự, Thần Số Học), kèm AI luận giải.",
};

type Props = {
  searchParams: Promise<{
    // Self
    birth?: string;
    gender?: string;
    hour?: string;
    name?: string;
    // Partner (đối tác)
    partnerBirth?: string;
    partnerGender?: string;
    partnerHour?: string;
    partnerName?: string;
  }>;
};

export default async function HopTuoiLamAnPage({ searchParams }: Props) {
  const sp = await searchParams;

  const birthISO = sp.birth ?? "";
  const birthDate = birthISO ? new Date(birthISO) : null;
  const birthValid = birthDate && !isNaN(birthDate.getTime());
  const gender = sp.gender === "Nam" || sp.gender === "Nữ" ? (sp.gender as "Nam" | "Nữ") : "Nam";
  const hour = sp.hour && /^\d+$/.test(sp.hour) ? parseInt(sp.hour, 10) : undefined;
  const hourValid = hour === undefined || (hour >= 0 && hour <= 23);

  const pBirthISO = sp.partnerBirth ?? "";
  const pBirthDate = pBirthISO ? new Date(pBirthISO) : null;
  const pBirthValid = pBirthDate && !isNaN(pBirthDate.getTime());
  const pGender =
    sp.partnerGender === "Nam" || sp.partnerGender === "Nữ"
      ? (sp.partnerGender as "Nam" | "Nữ")
      : "Nam";
  const pHour =
    sp.partnerHour && /^\d+$/.test(sp.partnerHour) ? parseInt(sp.partnerHour, 10) : undefined;
  const pHourValid = pHour === undefined || (pHour >= 0 && pHour <= 23);

  const deep =
    birthValid && pBirthValid && hourValid && pHourValid
      ? deepCompat(
          { birthDate: birthISO, gender, hour, fullName: sp.name },
          { birthDate: pBirthISO, gender: pGender, hour: pHour, fullName: sp.partnerName },
          "business"
        )
      : 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-8 text-center">
          <h1 className="font-display text-ink-primary text-3xl font-semibold lg:text-4xl">
            Hợp Tuổi Làm Ăn — Phân Tích Đa Phương Pháp
          </h1>
          <p className="text-ink-secondary mt-2 text-sm">
            Đối chiếu 4 hệ thống: Tử Vi truyền thống · Cung Hoàng Đạo · Bát Tự · Thần Số Học. Trọng
            số nghiêng về Mệnh và Cung Phi — yếu tố quyết định trong hợp tác kinh doanh.
          </p>
        </div>

        <form
          method="GET"
          className="border-stroke-subtle bg-bg-elevated/40 mb-8 grid gap-5 rounded-xl border p-5 lg:p-6"
        >
          <fieldset className="grid gap-3">
            <legend className="text-brand-gold text-xs tracking-wider uppercase">Bạn</legend>
            <div className="grid gap-3 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="birth" defaultValue={birthISO} required />
                </div>
              </div>
              <div>
                <label className="text-ink-muted block text-xs">Giới tính</label>
                <select
                  name="gender"
                  defaultValue={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="Nam">Nam</option>
                  <option value="Nữ">Nữ</option>
                </select>
              </div>
              <div>
                <label className="text-ink-muted block text-xs">
                  Giờ sinh (0–23, không bắt buộc)
                </label>
                <input
                  type="number"
                  name="hour"
                  defaultValue={hour ?? ""}
                  min={0}
                  max={23}
                  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 className="lg:col-span-2">
                <label className="text-ink-muted block text-xs">Họ tên (không bắt buộc)</label>
                <input
                  name="name"
                  defaultValue={sp.name ?? ""}
                  placeholder="Trần Hoàng Nam"
                  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>
          </fieldset>

          <fieldset className="grid gap-3">
            <legend className="text-brand-gold text-xs tracking-wider uppercase">Đối tác</legend>
            <div className="grid gap-3 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="partnerBirth" defaultValue={pBirthISO} />
                </div>
              </div>
              <div>
                <label className="text-ink-muted block text-xs">Giới tính</label>
                <select
                  name="partnerGender"
                  defaultValue={pGender}
                  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="Nam">Nam</option>
                  <option value="Nữ">Nữ</option>
                </select>
              </div>
              <div>
                <label className="text-ink-muted block text-xs">Giờ sinh (0–23)</label>
                <input
                  type="number"
                  name="partnerHour"
                  defaultValue={pHour ?? ""}
                  min={0}
                  max={23}
                  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 className="lg:col-span-2">
                <label className="text-ink-muted block text-xs">Họ tên (không bắt buộc)</label>
                <input
                  name="partnerName"
                  defaultValue={sp.partnerName ?? ""}
                  placeholder="Lê Văn Hùng"
                  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>
          </fieldset>

          <button
            type="submit"
            className="bg-brand-gold text-bg-base rounded-md px-4 py-2.5 text-sm font-semibold"
          >
            Phân tích đa phương pháp
          </button>
          <p className="text-ink-muted text-xs">
            Giờ sinh không bắt buộc. Có giờ sinh sẽ kích hoạt thêm phương pháp Bát Tự nhật chủ
            (chính xác hơn).
          </p>
        </form>

        {/* Deep compat result */}
        {deep ? (
          <article className="border-brand-gold/40 bg-bg-elevated/40 mb-6 rounded-2xl border-2 p-6 lg:p-8">
            <header className="border-stroke-subtle border-b pb-5">
              <div className="text-brand-gold flex items-center gap-2 text-xs tracking-[0.2em] uppercase">
                <Briefcase className="h-3.5 w-3.5" />
                Tổng hợp điểm 4 phương pháp · Hợp tác kinh doanh
              </div>
              <div className="mt-3 flex items-center justify-between gap-4">
                <div>
                  <h2
                    className={`font-display text-3xl font-bold lg:text-4xl ${
                      deep.totalScore >= 70
                        ? "text-emerald-400"
                        : deep.totalScore >= 55
                          ? "text-amber-400"
                          : "text-rose-400"
                    }`}
                  >
                    {deep.rating}
                  </h2>
                  <p className="text-ink-secondary mt-1 text-sm">
                    Điểm trung bình có trọng số · {deep.methods.length} phương pháp
                    {deep.hasHour ? "" : " (chưa nhập giờ sinh — thiếu Bát Tự)"}
                  </p>
                </div>
                <div className="font-display text-brand-gold text-5xl font-bold lg:text-6xl">
                  {deep.totalScore}
                  <span className="text-ink-muted text-base">/100</span>
                </div>
              </div>
              <p className="text-ink-secondary mt-4 text-sm leading-relaxed">{deep.hint}</p>
            </header>

            <div className="mt-5 space-y-3">
              {deep.methods.map((m) => (
                <details
                  key={m.key}
                  className="border-stroke-subtle/60 bg-bg-inset rounded-lg border p-4 [&_summary::-webkit-details-marker]:hidden"
                  open
                >
                  <summary className="flex cursor-pointer items-center justify-between gap-3">
                    <div className="min-w-0 flex-1">
                      <div className="text-ink-primary text-sm font-semibold">
                        {m.label}
                        <span className="text-ink-muted ml-2 font-mono text-xs">
                          (trọng số {m.weight}%)
                        </span>
                      </div>
                      <p className="text-ink-secondary mt-1 text-xs leading-relaxed">{m.summary}</p>
                    </div>
                    <div className="flex items-center gap-2">
                      <div
                        className={`font-display rounded-full px-3 py-1 text-sm font-bold ${
                          m.score >= 70
                            ? "bg-emerald-500/15 text-emerald-300"
                            : m.score >= 55
                              ? "bg-amber-500/15 text-amber-300"
                              : "bg-rose-500/15 text-rose-300"
                        }`}
                      >
                        {m.score}
                      </div>
                      <ChevronDown className="text-ink-muted h-4 w-4" />
                    </div>
                  </summary>
                  {m.details && m.details.length > 0 ? (
                    <div className="border-stroke-subtle/60 mt-4 grid gap-2 border-t pt-4 text-xs">
                      {m.details.map((d, i) => (
                        <div key={i} className="flex items-start gap-3">
                          <div className="text-ink-muted w-32 shrink-0 font-mono">{d.label}</div>
                          <div className="text-ink-secondary flex-1 leading-relaxed">
                            {d.note}
                            {d.max > 0 ? (
                              <span className="text-ink-muted ml-2 font-mono">
                                ({d.score}/{d.max})
                              </span>
                            ) : null}
                          </div>
                        </div>
                      ))}
                    </div>
                  ) : null}
                  <div className="mt-4">
                    <AiInsightPanel
                      topic="compat-method"
                      context={{
                        methodKey: m.key,
                        methodLabel: m.label,
                        score: m.score,
                        summary: m.summary,
                        details: m.details,
                        purpose: "business",
                        self: {
                          birthDate: birthISO,
                          gender,
                          hour,
                          name: sp.name,
                        },
                        partner: {
                          birthDate: pBirthISO,
                          gender: pGender,
                          hour: pHour,
                          name: sp.partnerName,
                        },
                      }}
                      cta={`Hỏi "Thầy" về ${m.label}`}
                      title={`"Thầy" luận giải — ${m.label}`}
                      hint={`Bấm để "Thầy" phân tích chuyên sâu cách ${m.label.toLowerCase()} nhìn cặp đối tác này, kèm điểm mạnh / rủi ro khi hợp tác kinh doanh.`}
                    />
                  </div>
                </details>
              ))}
            </div>
          </article>
        ) : null}

        {/* AI insight tổng */}
        {deep ? (
          <AiInsightPanel
            topic="numerology"
            context={{
              tool: "business-deep-compat",
              purpose: "business",
              self: {
                birthDate: birthISO,
                gender,
                hour,
                name: sp.name,
              },
              partner: {
                birthDate: pBirthISO,
                gender: pGender,
                hour: pHour,
                name: sp.partnerName,
              },
              totalScore: deep.totalScore,
              rating: deep.rating,
              methods: deep.methods.map((m) => ({
                label: m.label,
                score: m.score,
                weight: m.weight,
                summary: m.summary,
              })),
              hint: deep.hint,
              hasHour: deep.hasHour,
            }}
            cta={'Hỏi "Thầy" luận sâu'}
            title="Luận giải chuyên sâu cặp đối tác"
            hint='"Thầy" sẽ tổng hợp 4 phương pháp · phân tích vai trò phù hợp của mỗi người (đối ngoại / đối nội / tài chính / kỹ thuật), khuyến nghị về cấu trúc hợp tác và cách hoá giải xung khắc Mệnh-Cung.'
          />
        ) : null}

        {!birthValid ? (
          <div className="border-stroke-subtle bg-bg-elevated/40 rounded-xl border border-dashed p-6 text-center text-sm">
            <p className="text-ink-secondary">
              Nhập ngày sinh của bạn để bắt đầu. Thêm thông tin đối tác để xem so hợp đa phương
              pháp.
            </p>
          </div>
        ) : !pBirthValid ? (
          <div className="border-stroke-subtle bg-bg-elevated/40 rounded-xl border border-dashed p-6 text-center text-sm">
            <p className="text-ink-secondary">
              Nhập ngày sinh đối tác để xem so hợp 4 phương pháp.
            </p>
          </div>
        ) : null}
      </div>
    </div>
  );
}
