import type { Metadata } from "next";
import { TriangleAlert } from "lucide-react";
import { analyzePalm, type PalmistryInput } from "@/lib/palmistry/analyze";
import { PalmistryForm } from "@/components/palmistry/palmistry-form";
import { AiInsightPanel } from "@/components/ai/insight-panel";

export const metadata: Metadata = {
  title: "Bàn Tay Hình Long — Tử Vi Số",
  description:
    "Xem chỉ tay tự đánh giá hoặc tải ảnh để AI phân tích — 4 đường tay, hình bàn tay, tính cách, sự nghiệp.",
};

type SP = {
  shape?: string;
  heartL?: string;
  heartQ?: string;
  headL?: string;
  headQ?: string;
  lifeL?: string;
  lifeQ?: string;
  fateL?: string;
  fateQ?: string;
  thumb?: string;
  fingers?: string;
  venus?: string;
  jupiter?: string;
  marriage?: string;
};

type Props = { searchParams: Promise<SP> };

const VALID_LENGTH = ["long", "medium", "short", "absent", "unknown"] as const;
const VALID_QUALITY = ["clear", "broken", "chained", "forked", "unknown"] as const;
const VALID_SHAPE = ["earth", "air", "fire", "water", "unknown"] as const;

function pickLength(v?: string): PalmistryInput["heart"]["length"] {
  return (VALID_LENGTH as readonly string[]).includes(v ?? "")
    ? (v as PalmistryInput["heart"]["length"])
    : "unknown";
}
function pickQuality(v?: string): PalmistryInput["heart"]["quality"] {
  return (VALID_QUALITY as readonly string[]).includes(v ?? "")
    ? (v as PalmistryInput["heart"]["quality"])
    : "unknown";
}
function pickShape(v?: string): PalmistryInput["shape"] {
  return (VALID_SHAPE as readonly string[]).includes(v ?? "")
    ? (v as PalmistryInput["shape"])
    : "unknown";
}

export default async function PalmistryPage({ searchParams }: Props) {
  const sp = await searchParams;
  const hasInput =
    !!sp.shape || !!sp.heartL || !!sp.headL || !!sp.lifeL || !!sp.fateL || !!sp.thumb || !!sp.venus;

  const input: PalmistryInput = {
    dominantHand: "right",
    shape: pickShape(sp.shape),
    heart: { length: pickLength(sp.heartL), quality: pickQuality(sp.heartQ) },
    head: { length: pickLength(sp.headL), quality: pickQuality(sp.headQ) },
    life: { length: pickLength(sp.lifeL), quality: pickQuality(sp.lifeQ) },
    fate: { length: pickLength(sp.fateL), quality: pickQuality(sp.fateQ) },
    thumbStrong: sp.thumb === "1",
    fingersLong: sp.fingers === "1",
    mountVenus: sp.venus === "1",
    mountJupiter: sp.jupiter === "1",
    marriageLines: ((): 0 | 1 | 2 | 3 => {
      const n = parseInt(sp.marriage ?? "1", 10);
      return n >= 0 && n <= 3 ? (n as 0 | 1 | 2 | 3) : 1;
    })(),
  };

  const report = hasInput ? analyzePalm(input) : 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">
            Bàn Tay Hình Long
          </h1>
          <p className="text-ink-secondary mt-2 text-sm">
            Xem chỉ tay theo phương pháp truyền thống — tự đánh giá hoặc dùng &ldquo;Thầy&rdquo;
            quét ảnh.
          </p>
        </div>

        <article className="border-stroke-subtle bg-bg-elevated/40 mb-6 rounded-2xl border p-5 lg:p-6">
          <h2 className="font-display text-brand-gold text-xs font-semibold tracking-wider uppercase">
            Cách đọc
          </h2>
          <p className="text-ink-secondary mt-2 text-sm leading-relaxed">
            Mở bàn tay thuận của bạn (tay phải nếu thuận tay phải) trước nguồn sáng tốt. Tay trái
            được xem là &ldquo;tay bẩm sinh&rdquo;, tay thuận là &ldquo;tay vận hiện tại&rdquo; —
            khác biệt giữa 2 tay phản ánh hành trình bạn đã đi.
          </p>
          <p className="text-ink-muted mt-2 text-xs leading-relaxed">
            Lưu ý: Đường Mệnh ngắn KHÔNG có nghĩa đoản thọ. Kết quả mang tính tham khảo, không thay
            thế chẩn đoán chuyên môn.
          </p>
        </article>

        <PalmistryForm initial={sp as Record<string, string | undefined>} />

        {report ? (
          <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">
                    Đánh giá tổng hợp
                  </div>
                  <h2 className="font-display text-ink-primary mt-1 text-2xl font-semibold lg:text-3xl">
                    {report.rating}
                  </h2>
                </div>
                <div className="font-display text-brand-gold text-5xl font-bold lg:text-6xl">
                  {report.totalScore}
                  <span className="text-ink-muted text-lg">/100</span>
                </div>
              </div>
            </header>

            <div className="border-stroke-subtle/60 bg-bg-inset mt-5 rounded-lg border p-4">
              <h3 className="text-ink-primary text-sm font-medium">{report.shape.name}</h3>
              <p className="text-ink-secondary mt-1 text-xs leading-relaxed">{report.shape.desc}</p>
            </div>

            <div className="mt-5 space-y-3">
              <h3 className="font-display text-brand-gold text-xs font-semibold tracking-wider uppercase">
                4 đường chính
              </h3>
              {report.lines.map((line) => (
                <div
                  key={line.label}
                  className="border-stroke-subtle/60 bg-bg-inset rounded-lg border p-4"
                >
                  <div className="flex items-center justify-between">
                    <h4 className="text-ink-primary text-sm font-medium">{line.label}</h4>
                    <span className="text-brand-gold font-mono text-sm">{line.score}/25</span>
                  </div>
                  <div className="bg-bg-overlay/50 mt-2 h-1.5 w-full overflow-hidden rounded-full">
                    <div
                      className="bg-brand-gold h-full"
                      style={{ width: `${(line.score / 25) * 100}%` }}
                    />
                  </div>
                  <p className="text-ink-secondary mt-2 text-xs leading-relaxed">{line.finding}</p>
                </div>
              ))}
            </div>

            {report.highlights.length > 0 ? (
              <div className="mt-5 rounded-lg border border-amber-500/30 bg-amber-500/5 p-4">
                <h3 className="text-xs font-medium tracking-wider text-amber-300 uppercase">
                  Điểm nổi bật
                </h3>
                <ul className="text-ink-secondary mt-2 space-y-1 text-sm">
                  {report.highlights.map((h) => (
                    <li key={h} className="flex gap-2">
                      <span className="text-amber-400">★</span>
                      {h}
                    </li>
                  ))}
                </ul>
              </div>
            ) : null}

            <div className="mt-5 grid gap-3 lg:grid-cols-2">
              <div className="border-stroke-subtle/60 bg-bg-inset rounded-lg border p-4">
                <h3 className="text-ink-primary text-sm font-medium">Tính cách</h3>
                <ul className="text-ink-secondary mt-2 space-y-1 text-xs">
                  {report.personality.map((p) => (
                    <li key={p} className="flex gap-2">
                      <span className="text-brand-gold mt-0.5">·</span>
                      {p}
                    </li>
                  ))}
                </ul>
              </div>
              <div className="border-stroke-subtle/60 bg-bg-inset rounded-lg border p-4">
                <h3 className="text-ink-primary text-sm font-medium">Sự nghiệp</h3>
                <p className="text-ink-secondary mt-2 text-xs leading-relaxed">{report.career}</p>
              </div>
              <div className="border-stroke-subtle/60 bg-bg-inset rounded-lg border p-4">
                <h3 className="text-ink-primary text-sm font-medium">Tình duyên</h3>
                <p className="text-ink-secondary mt-2 text-xs leading-relaxed">
                  {report.relationship}
                </p>
              </div>
              <div className="border-stroke-subtle/60 bg-bg-inset rounded-lg border p-4">
                <h3 className="text-ink-primary text-sm font-medium">Sức khỏe</h3>
                <p className="text-ink-secondary mt-2 text-xs leading-relaxed">{report.health}</p>
              </div>
            </div>
          </article>
        ) : (
          <article className="border-stroke-subtle bg-bg-inset/40 rounded-xl border border-dashed p-6 text-center">
            <TriangleAlert className="text-ink-muted mx-auto h-8 w-8" />
            <p className="text-ink-muted mt-3 text-sm">
              Tải ảnh tay để AI gợi ý hoặc điền form bên trên rồi bấm{" "}
              <strong className="text-ink-secondary">Phân tích bàn tay</strong>.
            </p>
          </article>
        )}

        {report ? (
          <AiInsightPanel
            topic="numerology"
            context={{
              tool: "palmistry",
              shape: report.shape.name,
              totalScore: report.totalScore,
              rating: report.rating,
              lines: report.lines.map((l) => ({
                label: l.label,
                finding: l.finding,
                score: l.score,
              })),
              personality: report.personality,
              career: report.career,
              relationship: report.relationship,
              health: report.health,
              input: {
                shape: input.shape,
                heart: input.heart,
                head: input.head,
                life: input.life,
                fate: input.fate,
                marriageLines: input.marriageLines,
              },
            }}
            cta={'Hỏi "Thầy"'}
            title='Luận giải sâu bằng "Thầy"'
            hint='"Thầy" sẽ tổng hợp 4 đường tay + hình tay + đặc điểm phụ thành đoạn luận giải sâu hơn, đề xuất cách phát huy điểm mạnh và khắc phục điểm yếu.'
          />
        ) : null}
      </div>
    </div>
  );
}
