/**
 * Page chia sẻ giữa "Đặt Tên Con" và "Tên Công Ty".
 */
import type { NameAnalysis } from "@/lib/name-analysis";
import { analyzeName } from "@/lib/name-analysis";
import { NUMBER_MEANINGS } from "@/lib/numerology";
import { DateInput } from "@/components/ui/date-input";
import { AiInsightPanel } from "@/components/ai/insight-panel";
import { CheckCircle2, AlertCircle, Lightbulb } from "lucide-react";

export function NameAnalysisTool({
  searchParams,
  title,
  hint,
  mode,
}: {
  searchParams: { name?: string; date?: string; year?: string };
  title: string;
  hint: string;
  mode: "person" | "company";
}) {
  const name = searchParams.name?.trim() ?? "";
  let result: NameAnalysis | null = null;

  if (mode === "person" && searchParams.date) {
    const d = new Date(searchParams.date);
    if (!isNaN(d.getTime())) {
      result = analyzeName(name, {
        year: d.getFullYear(),
        month: d.getMonth() + 1,
        day: d.getDate(),
      });
    }
  } else if (mode === "company" && searchParams.year) {
    const y = parseInt(searchParams.year, 10);
    if (y > 1900 && y < 2200) {
      // Dùng 1/1 năm thành lập làm anchor
      result = analyzeName(name, { year: y, month: 1, day: 1 });
    }
  } else if (name) {
    result = analyzeName(name);
  }

  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">
            {title}
          </h1>
          <p className="text-ink-secondary mt-2 text-sm">{hint}</p>
        </div>

        <form
          method="GET"
          className="border-stroke-subtle bg-bg-elevated/40 mb-8 grid gap-4 rounded-xl border p-5 lg:grid-cols-2"
        >
          <div className="lg:col-span-2">
            <label className="text-ink-muted block text-xs">
              {mode === "person" ? "Họ và tên đầy đủ" : "Tên công ty đầy đủ"}
            </label>
            <input
              name="name"
              defaultValue={name}
              placeholder={mode === "person" ? "Nguyễn Văn An" : "Công ty TNHH ABC"}
              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>
          {mode === "person" ? (
            <div className="lg:col-span-2">
              <label className="text-ink-muted block text-xs">Ngày sinh dự kiến (dương lịch)</label>
              <div className="mt-1">
                <DateInput name="date" defaultValue={searchParams.date ?? ""} />
              </div>
            </div>
          ) : (
            <div className="lg:col-span-2">
              <label className="text-ink-muted block text-xs">
                Năm thành lập / Năm sinh chủ doanh nghiệp
              </label>
              <input
                type="number"
                name="year"
                defaultValue={searchParams.year ?? ""}
                placeholder="vd: 2026"
                min={1900}
                max={2200}
                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-2"
          >
            Phân tích
          </button>
        </form>

        {result ? (
          <>
            <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 className="min-w-0 flex-1">
                    <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 truncate text-2xl font-semibold lg:text-3xl">
                      {result.fullName}
                    </h2>
                  </div>
                  <div className="font-display text-brand-gold ml-4 text-5xl font-bold lg:text-6xl">
                    {result.totalScore}
                    <span className="text-ink-muted text-lg">/100</span>
                  </div>
                </div>
                <div className="text-ink-muted mt-1 text-xs">
                  {result.rating} · {result.syllables} tiếng · {result.letters} chữ ·{" "}
                  {result.vowels} nguyên âm
                </div>
              </header>

              {/* Per-syllable breakdown */}
              {result.syllableBreakdown.length > 1 ? (
                <div className="mt-5">
                  <div className="text-ink-muted mb-2 text-xs tracking-wider uppercase">
                    Cấu trúc {result.syllableBreakdown.length} tiếng
                  </div>
                  <div className="grid grid-cols-2 gap-2 sm:grid-cols-4">
                    {result.syllableBreakdown.map((s, i) => (
                      <div
                        key={i}
                        className="border-stroke-subtle/60 bg-bg-inset rounded-lg border px-3 py-2 text-center"
                      >
                        <div className="font-display text-ink-primary text-lg font-semibold">
                          {s.syllable}
                        </div>
                        <div className="text-ink-muted mt-0.5 text-[10px]">
                          {s.vowels} nguyên · {s.consonants} phụ
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              ) : null}

              <div className="mt-6 space-y-4">
                <Row
                  label="Số biểu cảm (Expression)"
                  value={result.expression}
                  desc={`${result.expressionMeaning}. ${NUMBER_MEANINGS[result.expression]?.desc ?? ""}`}
                />
                <Row
                  label="Số linh hồn (Soul Urge)"
                  value={result.soul}
                  desc={`${result.soulMeaning}. ${NUMBER_MEANINGS[result.soul]?.desc ?? ""}`}
                />
                <Row
                  label="Số tính cách (Personality)"
                  value={result.personality}
                  desc={`${result.personalityMeaning}. Phản ánh ấn tượng đầu tiên người khác cảm nhận.`}
                />
                <div className="border-stroke-subtle/60 bg-bg-inset rounded-lg border p-4">
                  <h3 className="text-ink-primary text-sm font-medium">Âm điệu &amp; độ dài</h3>
                  <p className="text-ink-secondary mt-1 text-xs leading-relaxed">
                    {result.rhythm.reason} (Điểm: {result.rhythm.score}/25)
                  </p>
                </div>
                {result.element ? (
                  <div className="border-stroke-subtle/60 bg-bg-inset rounded-lg border p-4">
                    <h3 className="text-ink-primary text-sm font-medium">Mệnh {result.element}</h3>
                    <p className="text-ink-secondary mt-1 text-xs leading-relaxed">
                      {result.elementHint}
                    </p>
                  </div>
                ) : null}
                {result.lifePathMatch ? (
                  <div
                    className={`border-stroke-subtle/60 rounded-lg border p-4 ${
                      result.lifePathMatch.match === "tốt"
                        ? "bg-emerald-500/5"
                        : result.lifePathMatch.match === "kỵ"
                          ? "bg-brand-red/5"
                          : "bg-bg-inset"
                    }`}
                  >
                    <h3 className="text-ink-primary text-sm font-medium">Khớp với Số chủ đạo</h3>
                    <p className="text-ink-secondary mt-1 text-xs leading-relaxed">
                      Số chủ đạo (Life Path): {result.lifePathMatch.lifePath} · Số biểu cảm:{" "}
                      {result.lifePathMatch.expression} → mức độ:{" "}
                      <span className="font-semibold">{result.lifePathMatch.match}</span>.
                      {result.lifePathMatch.match === "tốt"
                        ? " Tên này cộng hưởng tốt với con đường đời, hỗ trợ phát triển bản thân."
                        : result.lifePathMatch.match === "kỵ"
                          ? " Tên này có thể tạo lực cản tinh tế trong con đường đời. Cân nhắc tên thay thế."
                          : " Tên trung tính — không hỗ trợ đặc biệt cũng không cản trở."}
                    </p>
                  </div>
                ) : null}
              </div>
            </article>

            {/* Pros & Cons */}
            {result.pros.length > 0 || result.cons.length > 0 ? (
              <div className="mb-6 grid gap-4 lg:grid-cols-2">
                {result.pros.length > 0 ? (
                  <article className="rounded-2xl border border-emerald-500/30 bg-emerald-500/5 p-5">
                    <h3 className="text-ink-primary mb-3 flex items-center gap-2 text-sm font-semibold">
                      <CheckCircle2 className="h-4 w-4 text-emerald-400" />
                      Điểm mạnh
                    </h3>
                    <ul className="space-y-2">
                      {result.pros.map((p, i) => (
                        <li
                          key={i}
                          className="text-ink-secondary flex items-start gap-2 text-xs leading-relaxed"
                        >
                          <span className="mt-1 text-emerald-400">·</span>
                          {p}
                        </li>
                      ))}
                    </ul>
                  </article>
                ) : null}
                {result.cons.length > 0 ? (
                  <article className="rounded-2xl border border-rose-500/30 bg-rose-500/5 p-5">
                    <h3 className="text-ink-primary mb-3 flex items-center gap-2 text-sm font-semibold">
                      <AlertCircle className="h-4 w-4 text-rose-400" />
                      Điểm yếu
                    </h3>
                    <ul className="space-y-2">
                      {result.cons.map((c, i) => (
                        <li
                          key={i}
                          className="text-ink-secondary flex items-start gap-2 text-xs leading-relaxed"
                        >
                          <span className="mt-1 text-rose-400">·</span>
                          {c}
                        </li>
                      ))}
                    </ul>
                  </article>
                ) : null}
              </div>
            ) : null}

            {/* Suggestions */}
            {result.suggestions.length > 0 ? (
              <article className="border-brand-gold/30 bg-brand-gold/5 mb-6 rounded-2xl border p-5">
                <h3 className="text-ink-primary mb-3 flex items-center gap-2 text-sm font-semibold">
                  <Lightbulb className="text-brand-gold h-4 w-4" />
                  Gợi ý điều chỉnh
                </h3>
                <ul className="space-y-2">
                  {result.suggestions.map((s, i) => (
                    <li
                      key={i}
                      className="text-ink-secondary flex items-start gap-2 text-xs leading-relaxed"
                    >
                      <span className="text-brand-gold mt-1">→</span>
                      {s}
                    </li>
                  ))}
                </ul>
              </article>
            ) : null}

            {/* AI luận giải */}
            <AiInsightPanel
              topic="naming"
              context={{
                name: result.fullName,
                mode,
                birth: searchParams.date,
                year: searchParams.year,
                expression: result.expression,
                expressionMeaning: result.expressionMeaning,
                soul: result.soul,
                soulMeaning: result.soulMeaning,
                personality: result.personality,
                personalityMeaning: result.personalityMeaning,
                rhythm: result.rhythm,
                element: result.element,
                lifePathMatch: result.lifePathMatch,
                totalScore: result.totalScore,
                rating: result.rating,
                pros: result.pros,
                cons: result.cons,
                suggestions: result.suggestions,
              }}
              cta={'Hỏi "Thầy" về tên này'}
              title={
                mode === "person"
                  ? '"Thầy" luận giải tên & gợi ý đổi'
                  : '"Thầy" luận thương hiệu & gợi ý đổi'
              }
              hint={
                mode === "person"
                  ? '"Thầy" sẽ phân tích sâu hơn về âm sắc, ảnh hưởng đến tính cách bé và gợi ý 3 biến thể tên cụ thể có Số biểu cảm tốt hơn.'
                  : '"Thầy" sẽ phân tích thương hiệu này về phong thuỷ doanh nghiệp + gợi ý 3 biến thể tên thương hiệu thay thế cụ thể.'
              }
            />
          </>
        ) : null}
      </div>
    </div>
  );
}

function Row({ label, value, desc }: { label: string; value: number; desc: string }) {
  return (
    <div className="border-stroke-subtle/60 bg-bg-inset flex items-start gap-4 rounded-lg border p-4">
      <div className="bg-brand-gold text-bg-base font-display flex h-12 w-12 shrink-0 items-center justify-center rounded-lg text-xl font-bold">
        {value}
      </div>
      <div className="min-w-0 flex-1">
        <div className="text-ink-primary text-sm font-medium">{label}</div>
        <p className="text-ink-secondary mt-1 text-xs leading-relaxed">{desc}</p>
      </div>
    </div>
  );
}
