"use client";

import Link from "next/link";
import { useEffect, useState } from "react";

import { fetchBirthTimeReconstructionResult } from "./api";
import type { BirthTimeReconstructionPublicResult, CandidateDetail } from "./schema";

function confidenceBadgeClass(level: string | undefined): string {
  switch (level) {
    case "high":
      return "border-emerald-800/50 bg-emerald-950/30 text-emerald-200/95";
    case "medium":
      return "border-amber-800/45 bg-amber-950/25 text-amber-100/90";
    default:
      return "border-stone-700/60 bg-stone-950/40 text-stone-300";
  }
}

function confidenceLabelVi(level: string | undefined): string {
  switch (level) {
    case "high":
      return "Cao (heuristic)";
    case "medium":
      return "Trung bình (heuristic)";
    default:
      return "Thấp (heuristic)";
  }
}

export function BirthTimeReconstructionResultView({ id }: { id: string }) {
  const [data, setData] = useState<BirthTimeReconstructionPublicResult | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let cancelled = false;
    (async () => {
      setLoading(true);
      setError(null);
      try {
        const res = await fetchBirthTimeReconstructionResult(id);
        if (!cancelled) setData(res);
      } catch (e) {
        if (!cancelled) setError(e instanceof Error ? e.message : "Không tải được.");
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [id]);

  if (loading) {
    return (
      <div className="rounded-xl border border-stone-800/60 bg-[#0c0b0a]/55 px-5 py-12 text-center text-sm text-stone-500">
        Đang mở kết quả…
      </div>
    );
  }

  if (error || !data) {
    return (
      <div className="rounded-xl border border-red-900/35 bg-red-950/20 px-5 py-8 text-center text-sm text-red-200/90">
        <p>{error ?? "Không có dữ liệu."}</p>
        <Link href="/birth-time-reconstruction" className="ctkp-text-link mt-4 inline-block text-sm">
          Quay lại biểu mẫu
        </Link>
      </div>
    );
  }

  const details = data.topCandidatesDetail?.length ? data.topCandidatesDetail : null;
  const rows = details ?? data.candidates.map((c) => ({ labelVi: c.labelVi, weightPct: c.weightPct, matchedReasons: c.matchedReasons }));
  const top = rows[0];
  const rest = rows.slice(1);
  const primaryDetail: CandidateDetail | undefined = details?.[0];

  return (
    <div className="space-y-8">
      <header className="text-center">
        <p className="ctkp-eyebrow text-[10px] tracking-[0.28em]">
          Gợi ý giờ sinh · {data.scoringVersion ?? "—"}
        </p>
        <h1 className="font-ctkp-display mt-4 text-pretty text-2xl font-semibold text-[color:var(--ctkp-text-main)] sm:text-3xl">
          Khung giờ khả dĩ (heuristic)
        </h1>
        <p className="mx-auto mt-4 max-w-xl text-sm leading-relaxed text-[color:var(--ctkp-text-secondary)]">
          Đây là tái hiện xác suất từ luật đời sống — không thay thế lá số hay engine tử vi. Kết quả mang tính thử nghiệm.
        </p>
        <div className="mx-auto mt-5 flex flex-wrap items-center justify-center gap-3">
          <span
            className={`inline-flex rounded-full border px-3 py-1 text-xs font-medium tracking-wide ${confidenceBadgeClass(data.confidenceLevel)}`}
          >
            Độ tin cậy: {data.confidenceLabel ?? confidenceLabelVi(data.confidenceLevel)}
          </span>
          {data.scoringVersion ? (
            <span className="text-xs text-stone-500">
              Phiên bản: <span className="text-stone-400">{data.scoringVersion}</span>
            </span>
          ) : null}
        </div>
      </header>

      {data.refinementEligible === true && data.refinementApplied !== true ? (
        <div className="rounded-xl border border-amber-800/35 bg-amber-950/20 px-4 py-4 text-center sm:px-5">
          <p className="text-sm text-stone-300/95">
            Các khung giờ đầu bảng còn gần nhau hoặc độ tin cậy chưa cao — bạn có thể trả lời thêm vài câu để tăng độ
            tách (ước lượng).
          </p>
          <Link
            href={`/birth-time-reconstruction/result/${id}/refine`}
            className="mt-3 inline-flex rounded-lg bg-gradient-to-r from-amber-900/70 to-amber-700/50 px-5 py-2.5 text-sm font-medium text-amber-50"
          >
            Tinh chỉnh kết quả
          </Link>
        </div>
      ) : null}

      {data.completeness ? (
        <p className="text-center text-xs text-stone-500">
          Độ đầy đủ câu trả lời:{" "}
          <span className="text-stone-400">
            {Math.round(data.completeness.score0to1 * 100)}% ({data.completeness.filledFields}/{data.completeness.totalFields} mục)
          </span>
        </p>
      ) : null}

      {data.warnings && data.warnings.length > 0 ? (
        <section
          aria-label="Cảnh báo dữ liệu"
          className="rounded-xl border border-amber-900/30 bg-amber-950/15 px-4 py-3 text-sm text-amber-100/90"
        >
          <ul className="list-inside list-disc space-y-1">
            {data.warnings.map((w) => (
              <li key={w}>{w}</li>
            ))}
          </ul>
        </section>
      ) : null}

      {data.initialSnapshot && data.refinementApplied ? (
        <section
          aria-labelledby="btr-initial-heading"
          className="rounded-xl border border-stone-800/70 bg-[#080706]/80 px-5 py-5 sm:px-6"
        >
          <h2 id="btr-initial-heading" className="ctkp-form-section-label">
            Kết quả ban đầu (trước tinh chỉnh)
          </h2>
          <div className="ctkp-form-section-rule mb-4" aria-hidden />
          <ul className="space-y-2 text-sm text-stone-400">
            {(data.initialSnapshot.topCandidatesDetail ?? data.initialSnapshot.candidates).slice(0, 3).map((c) => (
              <li key={`init-${c.labelVi}`} className="flex justify-between gap-2">
                <span>{c.labelVi}</span>
                <span className="tabular-nums text-stone-300">{c.weightPct}%</span>
              </li>
            ))}
          </ul>
          <p className="mt-3 text-xs text-stone-600">
            Độ tin cậy lúc đó: {data.initialSnapshot.confidenceLabel ?? "—"} · khoảng cách top 1–2:{" "}
            {data.initialSnapshot.gapTop1Top2Pct}% điểm phần trăm (ước lượng).
          </p>
        </section>
      ) : null}

      {top ? (
        <section aria-labelledby="btr-top-heading" className="rounded-xl border border-amber-700/35 bg-gradient-to-b from-[#14110d]/90 to-[#0c0b0a]/90 px-5 py-7 sm:px-8">
          <h2 id="btr-top-heading" className="ctkp-form-section-label">
            {data.refinementApplied ? "Sau khi tinh chỉnh — khung giờ ưu tiên" : "Khung giờ được ưu tiên nhất"}
          </h2>
          <div className="ctkp-form-section-rule mb-5" aria-hidden />
          <div className="flex flex-wrap items-end justify-between gap-4">
            <div>
              <p className="text-2xl font-semibold text-amber-50/95 sm:text-3xl">{top.labelVi}</p>
              {"rawScore" in top && top.rawScore != null ? (
                <p className="mt-1 text-xs text-stone-500">Điểm thô (tương đối): {top.rawScore}</p>
              ) : null}
            </div>
            <p className="font-ctkp-display text-3xl tabular-nums text-amber-200/95 sm:text-4xl">{top.weightPct}%</p>
          </div>
          {top.matchedReasons && top.matchedReasons.length > 0 ? (
            <ul className="mt-5 space-y-2 text-sm leading-relaxed text-stone-300/95">
              {top.matchedReasons.slice(0, 6).map((m) => (
                <li key={`${m.ruleId}-${m.textVi.slice(0, 24)}`} className="border-l-2 border-amber-800/40 pl-3">
                  <span className="text-[10px] uppercase tracking-wider text-stone-500">{m.category}</span>
                  <span className="sr-only"> — </span>
                  <span className="mt-0.5 block text-stone-300/95">{m.textVi}</span>
                </li>
              ))}
            </ul>
          ) : null}
        </section>
      ) : null}

      {rest.length > 0 ? (
        <section aria-labelledby="btr-rest-heading">
          <h2 id="btr-rest-heading" className="ctkp-form-section-label mb-4">
            So sánh thêm (top {rest.length})
          </h2>
          <div className="grid gap-3 sm:grid-cols-2">
            {rest.map((c) => (
              <div
                key={c.labelVi}
                className="rounded-xl border border-stone-800/70 bg-[#0c0b0a]/55 px-4 py-4"
              >
                <div className="flex items-baseline justify-between gap-2">
                  <span className="text-base text-amber-100/95">{c.labelVi}</span>
                  <span className="font-ctkp-display text-xl tabular-nums text-amber-200/85">{c.weightPct}%</span>
                </div>
                {c.matchedReasons && c.matchedReasons.length > 0 ? (
                  <p className="mt-2 line-clamp-3 text-xs leading-relaxed text-stone-500">{c.matchedReasons[0]?.textVi}</p>
                ) : null}
              </div>
            ))}
          </div>
        </section>
      ) : null}

      {data.chartBridge?.applied && data.chartBridge.fallback ? (
        <section
          aria-label="Đối chiếu lá số không khả dụng"
          className="rounded-xl border border-amber-900/25 bg-amber-950/15 px-4 py-3 text-sm text-amber-100/85"
        >
          <p className="font-medium text-amber-100/90">Đối chiếu lá số</p>
          <p className="mt-2 text-xs leading-relaxed text-stone-400">
            {data.chartBridge.reasonVi ??
              "Không tạo đủ lá ứng viên — hệ thống chỉ dùng lớp heuristic cho bảng xếp hạng."}
          </p>
        </section>
      ) : null}

      {data.chartBridge?.applied && !data.chartBridge.fallback && primaryDetail ? (
        <section
          aria-labelledby="btr-chart-heading"
          className="rounded-xl border border-stone-800/65 bg-[#0a0908]/90 px-5 py-5 sm:px-6"
        >
          <h2 id="btr-chart-heading" className="ctkp-form-section-label">
            Đối chiếu lá số (tín hiệu rút gọn)
          </h2>
          <div className="ctkp-form-section-rule mb-4" aria-hidden />
          <p className="text-xs leading-relaxed text-stone-500">
            Trọng số gộp: heuristic ~{(data.chartBridge.weights.heuristic * 100).toFixed(0)}% · đối chiếu lá số ~
            {(data.chartBridge.weights.astrology * 100).toFixed(0)}% — không dùng AI, chỉ so khớp tín hiệu cung/sao với dữ
            liệu bạn nhập.
          </p>
          {primaryDetail.heuristicWeightPct != null && primaryDetail.astrologyWeightPct != null ? (
            <p className="mt-2 text-xs text-stone-500">
              Ứng viên đầu bảng — phần chia trước khi gộp: heuristic ~{primaryDetail.heuristicWeightPct}% · đối chiếu ~
              {primaryDetail.astrologyWeightPct}%.
            </p>
          ) : null}
          {primaryDetail.chartLight ? (
            <p className="mt-3 text-xs text-stone-400">
              Cục: {primaryDetail.chartLight.menhCucJuNameVi} · nạp âm Mệnh: {primaryDetail.chartLight.menhNayinElement}
            </p>
          ) : null}
          {primaryDetail.chartFeatureMatched && primaryDetail.chartFeatureMatched.length > 0 ? (
            <div className="mt-4">
              <p className="text-[10px] font-medium uppercase tracking-wider text-emerald-200/70">Khớp</p>
              <ul className="mt-1 list-inside list-disc space-y-1 text-xs text-stone-300/95">
                {primaryDetail.chartFeatureMatched.slice(0, 5).map((m) => (
                  <li key={m} className="font-mono text-[11px] text-stone-400">
                    {m}
                  </li>
                ))}
              </ul>
            </div>
          ) : null}
          {primaryDetail.chartFeatureMismatched && primaryDetail.chartFeatureMismatched.length > 0 ? (
            <div className="mt-4">
              <p className="text-[10px] font-medium uppercase tracking-wider text-amber-200/70">Lệch</p>
              <ul className="mt-1 list-inside list-disc space-y-1 text-xs text-stone-400">
                {primaryDetail.chartFeatureMismatched.slice(0, 4).map((m) => (
                  <li key={m} className="font-mono text-[11px] text-stone-500">
                    {m}
                  </li>
                ))}
              </ul>
            </div>
          ) : null}
          {primaryDetail.combinedExplanationLines && primaryDetail.combinedExplanationLines.length > 0 ? (
            <ul className="mt-4 space-y-2 text-xs leading-relaxed text-stone-400">
              {primaryDetail.combinedExplanationLines.slice(0, 3).map((line, i) => (
                <li key={`exp-${i}`}>{line}</li>
              ))}
            </ul>
          ) : null}
        </section>
      ) : null}

      {data.refinementMeta ? (
        <section className="rounded-xl border border-stone-800/60 px-5 py-6">
          <h2 className="text-sm font-medium uppercase tracking-wider text-stone-400">Vì sao kết quả thay đổi?</h2>
          <p className="mt-3 text-sm leading-relaxed text-stone-400">
            Đã thêm {data.refinementMeta.questionIds.length} tín hiệu tinh chỉnh. Khoảng cách top 1–2:{" "}
            {data.refinementMeta.gapTop1Top2BeforePct}% → {data.refinementMeta.gapTop1Top2AfterPct}% (ước lượng, không đảm bảo
            đúng giờ sinh thực).
          </p>
          {data.refinementMeta.gapTop1Top2AfterPct > data.refinementMeta.gapTop1Top2BeforePct ? (
            <p className="mt-2 text-xs text-emerald-200/70">Có dấu hiệu tách rõ hơn giữa các khung giờ đầu bảng.</p>
          ) : null}
        </section>
      ) : null}

      <section className="rounded-xl border border-stone-800/60 bg-[#0c0b0a]/55 px-5 py-6 sm:px-7">
        <h2 className="text-sm font-medium uppercase tracking-wider text-stone-400">Vì sao có kết quả này?</h2>
        <p className="mt-3 text-sm leading-relaxed text-stone-300/95">{data.explanationNoteVi}</p>
        {data.matchedRuleCount != null ? (
          <p className="mt-3 text-xs text-stone-500">Số luật khớp: {data.matchedRuleCount}</p>
        ) : null}
      </section>

      <section className="rounded-xl border border-stone-800/55 px-5 py-6">
        <h2 className="text-sm font-medium uppercase tracking-wider text-stone-400">Những tín hiệu còn chưa chắc chắn</h2>
        <p className="mt-3 text-sm text-stone-500">
          Mô hình vẫn là xác suất — có thể còn chồng lấn giữa vài khung giờ. Thông tin thêm hoặc engine tử vi sau này có thể
          thu hẹp tiếp.
        </p>
      </section>

      <section className="rounded-xl border border-stone-800/55 px-5 py-6">
        <h2 className="text-sm font-medium uppercase tracking-wider text-stone-400">Làm sao cải thiện độ chính xác?</h2>
        <ul className="mt-3 list-inside list-disc space-y-2 text-sm text-stone-400">
          <li>Bổ sung thêm mốc năm (kết hôn, con, nghề) và khoảng tuổi rõ ràng hơn.</li>
          <li>Ghi rõ sự kiện lớn (mỗi dòng một ý) trong phần sự kiện đời.</li>
          <li>Mô tả ngắn quan hệ cha mẹ và trăn trở hiện tại — giúp luật từ khóa khớp tốt hơn.</li>
          <li>Sau này có thể gắn engine tử vi để tinh chỉnh, không chỉ heuristic.</li>
        </ul>
      </section>

      {data.overallNotesVi && data.overallNotesVi.length > 0 ? (
        <section className="rounded-xl border border-amber-900/25 bg-amber-950/15 px-5 py-6 sm:px-7">
          <h2 className="text-sm font-medium uppercase tracking-wider text-amber-200/70">Ghi chú</h2>
          <ul className="mt-3 space-y-2 text-sm leading-relaxed text-stone-300/95">
            {data.overallNotesVi.map((n) => (
              <li key={n}>{n}</li>
            ))}
          </ul>
        </section>
      ) : null}

      <section className="rounded-xl border border-stone-800/60 px-5 py-6 text-sm leading-relaxed text-stone-500">
        <p>
          <button
            type="button"
            disabled
            className="w-full cursor-not-allowed rounded-lg border border-stone-800/80 bg-stone-950/40 px-4 py-3 text-center text-stone-500 sm:w-auto"
          >
            Mở khóa phân tích chi tiết (sắp có)
          </button>
        </p>
      </section>

      <nav className="flex flex-wrap justify-center gap-4 text-sm">
        <Link href="/birth-time-reconstruction" className="ctkp-text-link">
          Làm lại biểu mẫu
        </Link>
        <Link href="/tu-vi" className="ctkp-text-link">
          Sang lá số (khi đã có giờ)
        </Link>
      </nav>
    </div>
  );
}
