import type { Metadata } from "next";
import { Phone, Sparkles, Star } from "lucide-react";
import { analyzePhoneNumber } from "@/lib/phone-luck";
import { AiInsightPanel } from "@/components/ai/insight-panel";

export const metadata: Metadata = {
  title: "Số Điện Thoại Hợp Mệnh — Tử Vi Số",
  description:
    "Phân tích số điện thoại theo Bát Tinh, cá nhân hóa theo cung mệnh từ năm sinh và giới tính.",
};

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

function pickInt(s: string | undefined, min: number, max: number): number | undefined {
  if (!s) return undefined;
  const n = parseInt(s, 10);
  if (Number.isNaN(n) || n < min || n > max) return undefined;
  return n;
}

export default async function PhonePage({ searchParams }: Props) {
  const sp = await searchParams;
  const phone = (sp.phone ?? "").trim();
  const year = pickInt(sp.year, 1900, 2100);
  const gender = sp.gender === "Nữ" ? "Nữ" : sp.gender === "Nam" ? "Nam" : undefined;

  const result = phone
    ? analyzePhoneNumber(phone, year && gender ? { birthYear: year, gender } : undefined)
    : 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ố Điện Thoại Hợp Mệnh
          </h1>
          <p className="text-ink-secondary mt-2 text-sm">
            Phân tích theo Bát Tinh, cá nhân hóa theo cung mệnh nếu nhập năm sinh và giới tính.
          </p>
        </div>

        <form
          method="GET"
          className="border-stroke-subtle bg-bg-elevated/40 mb-6 rounded-xl border p-4 lg:p-5"
        >
          <div className="space-y-3">
            <div>
              <label className="text-ink-muted block text-xs">Số điện thoại</label>
              <div className="relative mt-1.5">
                <Phone className="text-ink-muted absolute top-1/2 left-3 h-4 w-4 -translate-y-1/2" />
                <input
                  name="phone"
                  defaultValue={phone}
                  placeholder="vd: 0901234567"
                  required
                  className="bg-bg-inset border-stroke-default text-ink-primary focus:border-brand-gold w-full rounded-md border py-2.5 pr-3 pl-9 font-mono text-sm focus:outline-none"
                />
              </div>
            </div>

            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="text-ink-muted block text-xs">
                  Năm sinh <span className="text-ink-muted/70 font-normal">(không bắt buộc)</span>
                </label>
                <input
                  type="number"
                  name="year"
                  defaultValue={year ?? ""}
                  placeholder="vd: 1990"
                  min={1900}
                  max={2100}
                  className="bg-bg-inset border-stroke-default text-ink-primary focus:border-brand-gold mt-1.5 w-full rounded-md border px-3 py-2.5 text-sm focus:outline-none"
                />
              </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.5 w-full rounded-md border px-3 py-2.5 text-sm focus:outline-none"
                >
                  <option value="">— chọn —</option>
                  <option value="Nam">Nam</option>
                  <option value="Nữ">Nữ</option>
                </select>
              </div>
            </div>

            <p className="text-ink-muted text-[11px] leading-relaxed">
              Nhập năm sinh và giới tính để được phân tích cá nhân hóa theo cung mệnh (Đông/Tây tứ
              mệnh). Nếu không nhập, chỉ phân tích chung theo Bát Tinh.
            </p>
          </div>

          <button
            type="submit"
            className="bg-brand-gold text-bg-base mt-4 w-full rounded-md px-4 py-2 text-sm font-semibold"
          >
            Phân tích
          </button>
        </form>

        {result ? (
          <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">
                    Số rút gọn · {result.totalMeaning.title}
                  </div>
                  <div className="text-ink-primary mt-1 font-mono text-lg">{result.digits}</div>
                </div>
                <div className="font-display text-brand-gold text-5xl font-bold">
                  {result.catScore}
                  <span className="text-ink-muted text-base">%</span>
                </div>
              </div>
              <div className="text-ink-muted mt-1 text-xs">% cặp số cát (chung)</div>
            </header>

            <p className="text-ink-secondary mt-4 text-sm leading-relaxed">
              {result.totalMeaning.desc}
            </p>

            {/* Personalized panel */}
            {result.personalized ? (
              <div className="border-brand-gold/40 bg-brand-gold/5 mt-6 rounded-xl border p-4 lg:p-5">
                <div className="flex items-start gap-3">
                  <Sparkles className="text-brand-gold mt-0.5 h-5 w-5 flex-shrink-0" />
                  <div className="flex-1">
                    <div className="flex flex-wrap items-baseline justify-between gap-2">
                      <h3 className="font-display text-ink-primary text-base font-semibold lg:text-lg">
                        Phân tích cá nhân hóa
                      </h3>
                      <div className="font-display text-brand-gold text-3xl font-bold">
                        {result.personalized.matchScore}
                        <span className="text-ink-muted text-base">%</span>
                      </div>
                    </div>
                    <div className="text-ink-muted mt-0.5 text-[11px] tracking-wider uppercase">
                      Mức độ hợp với mệnh của bạn
                    </div>
                    <p className="text-ink-secondary mt-2 text-sm leading-relaxed">
                      {result.personalized.summary}
                    </p>

                    <div className="mt-3 grid grid-cols-2 gap-2 text-xs lg:text-sm">
                      <div className="bg-bg-inset/60 rounded-md px-3 py-2">
                        <div className="text-ink-muted text-[10px] tracking-wider uppercase">
                          Cung mệnh
                        </div>
                        <div className="text-brand-gold font-display mt-0.5 text-lg font-semibold">
                          {result.personalized.cungMenh}
                        </div>
                      </div>
                      <div className="bg-bg-inset/60 rounded-md px-3 py-2">
                        <div className="text-ink-muted text-[10px] tracking-wider uppercase">
                          Nhóm
                        </div>
                        <div className="text-ink-primary font-display mt-0.5 text-lg font-semibold">
                          {result.personalized.group}
                        </div>
                      </div>
                    </div>

                    <div className="mt-3">
                      <div className="text-ink-muted mb-1.5 text-[10px] tracking-wider uppercase">
                        Quẻ hợp mệnh (theo thứ tự ưu tiên)
                      </div>
                      <div className="flex flex-wrap gap-1.5">
                        {result.personalized.auspiciousFortunes.map((f, i) => (
                          <span
                            key={f}
                            className={
                              i === 0
                                ? "rounded-full border border-amber-400/40 bg-amber-500/15 px-2.5 py-0.5 text-xs font-medium text-amber-300"
                                : "border-stroke-default text-ink-secondary rounded-full border px-2.5 py-0.5 text-xs"
                            }
                          >
                            {i === 0 ? "★ " : ""}
                            {f}
                          </span>
                        ))}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            ) : (
              <div className="border-stroke-subtle bg-bg-inset/40 mt-6 rounded-lg border border-dashed p-3 text-center text-xs">
                <span className="text-ink-muted">
                  💡 Nhập <strong className="text-ink-secondary">năm sinh</strong> và{" "}
                  <strong className="text-ink-secondary">giới tính</strong> để xem phân tích cá nhân
                  hóa theo cung mệnh
                </span>
              </div>
            )}

            <div className="mt-6">
              <h3 className="font-display text-brand-gold mb-3 text-sm font-semibold tracking-wider uppercase">
                Phân tích từng cặp
              </h3>
              <div className="space-y-1.5">
                {result.pairs.map((p, i) => (
                  <div
                    key={i}
                    className={`border-stroke-subtle/60 flex items-center gap-3 rounded-md border p-2 ${
                      p.type === "Cát"
                        ? "bg-emerald-500/5"
                        : p.type === "Hung"
                          ? "bg-brand-red/5"
                          : "bg-bg-inset"
                    } ${p.matchesMenh ? "ring-1 ring-amber-400/40" : ""}`}
                  >
                    <span className="bg-bg-overlay/60 text-ink-primary rounded px-2 py-1 font-mono font-bold">
                      {p.pair}
                    </span>
                    <span
                      className={`text-xs font-medium ${
                        p.type === "Cát"
                          ? "text-emerald-400"
                          : p.type === "Hung"
                            ? "text-brand-red"
                            : "text-ink-muted"
                      }`}
                    >
                      {p.type}
                    </span>
                    {p.matchesMenh ? (
                      <Star
                        className="h-3 w-3 text-amber-400"
                        fill="currentColor"
                        aria-label="Hợp mệnh"
                      />
                    ) : null}
                    <span className="text-ink-secondary text-xs">{p.meaning}</span>
                  </div>
                ))}
              </div>
              {result.personalized ? (
                <p className="text-ink-muted mt-3 text-[11px]">
                  ★ = cặp số rơi vào quẻ thuộc nhóm cát của mệnh{" "}
                  <strong className="text-ink-secondary">{result.personalized.cungMenh}</strong>
                </p>
              ) : null}
            </div>
          </article>
        ) : (
          <p className="text-ink-muted text-center text-sm">Nhập số điện thoại để phân tích.</p>
        )}

        {result ? (
          <div className="mt-6">
            <AiInsightPanel
              topic="numerology"
              context={{
                tool: "phone-luck",
                phone: result.digits,
                catScore: result.catScore,
                totalMeaning: result.totalMeaning,
                pairs: result.pairs,
                personalized: result.personalized
                  ? {
                      cungMenh: result.personalized.cungMenh,
                      group: result.personalized.group,
                      matchScore: result.personalized.matchScore,
                      summary: result.personalized.summary,
                      auspiciousFortunes: result.personalized.auspiciousFortunes,
                    }
                  : null,
              }}
              cta={'Hỏi "Thầy" về số này'}
              title='"Thầy" luận sâu số điện thoại'
              hint={
                result.personalized
                  ? '"Thầy" sẽ phân tích sâu chuỗi số này với cung mệnh của bạn, gợi ý 3 đoạn số thay thế nếu cần đổi và cách dùng số này hỗ trợ tài lộc / công việc.'
                  : '"Thầy" sẽ phân tích sâu chuỗi số theo Bát Tinh và gợi ý 3 chuỗi số tốt hơn nếu cần đổi.'
              }
            />
          </div>
        ) : null}
      </div>
    </div>
  );
}
