"use client";

import { useCallback, useEffect, useRef, useState } from "react";

import {
  getTuViRevisitInsightsBundle,
  type TuViRevisitInsightsBundle,
  type TuViRevisitInsightsPayload,
} from "@/lib/saved-tu-vi-readings-api";
import { pickTuViFunnelPayload, queueTuViFunnelTelemetry, TUVI_FUNNEL_EVENT } from "@/lib/tuvi-funnel-telemetry.v1";

function bulletCount(ins: TuViRevisitInsightsPayload): number {
  return (
    ins.recurringThemes.length +
    ins.recurringStrengths.length +
    ins.recurringRisks.length +
    ins.shiftingFocusAreas.length +
    ins.timingChanges.length +
    ins.confidenceNotes.length
  );
}

function InsightList({ title, items }: { title: string; items: readonly string[] }) {
  if (!items.length) return null;
  return (
    <div className="mt-4">
      <h3 className="text-[11px] font-semibold uppercase tracking-wide text-amber-200/75">{title}</h3>
      <ul className="mt-2 list-inside list-disc space-y-1.5 text-[13px] leading-snug text-stone-300">
        {items.map((x) => (
          <li key={x}>{x}</li>
        ))}
      </ul>
    </div>
  );
}

export function TuViRevisitInsightsSection() {
  const [bundle, setBundle] = useState<TuViRevisitInsightsBundle | null>(null);
  const [phase, setPhase] = useState<"idle" | "loading" | "err">("idle");
  const viewSent = useRef(false);
  const expandSent = useRef(false);

  const sendExpand = useCallback((b: TuViRevisitInsightsBundle) => {
    if (expandSent.current) return;
    expandSent.current = true;
    queueTuViFunnelTelemetry({
      eventType: TUVI_FUNNEL_EVENT.revisit_insight_expand,
      payload: pickTuViFunnelPayload({
        source: "account_revisit_panel",
        path: "/account",
        totalSavedReadings: b.totalSavedReadings,
        largestBirthGroupSize: b.largestBirthGroupSize,
        revisitInsightBulletCount: bulletCount(b.insights),
      }),
    });
  }, []);

  useEffect(() => {
    let cancel = false;
    setPhase("loading");
    void (async () => {
      try {
        const b = await getTuViRevisitInsightsBundle();
        if (cancel) return;
        setBundle(b);
        setPhase("idle");
        if (!viewSent.current && b.totalSavedReadings > 0) {
          viewSent.current = true;
          queueTuViFunnelTelemetry({
            eventType: TUVI_FUNNEL_EVENT.revisit_insight_view,
            payload: pickTuViFunnelPayload({
              source: "account_revisit_panel",
              path: "/account",
              totalSavedReadings: b.totalSavedReadings,
              largestBirthGroupSize: b.largestBirthGroupSize,
              revisitInsightBulletCount: bulletCount(b.insights),
            }),
          });
        }
      } catch {
        if (!cancel) setPhase("err");
      }
    })();
    return () => {
      cancel = true;
    };
  }, []);

  if (phase === "loading" && !bundle) {
    return (
      <section className="rounded-2xl border border-amber-950/25 bg-stone-950/35 px-5 py-6 sm:px-7 sm:py-8">
        <p className="text-sm text-stone-500">Đang tải phần so sánh các lần lưu…</p>
      </section>
    );
  }

  if (phase === "err" || !bundle) return null;

  if (bundle.totalSavedReadings === 0) return null;

  if (bundle.totalSavedReadings === 1 || bundle.largestBirthGroupSize < 2) {
    return (
      <section className="rounded-2xl border border-amber-950/25 bg-stone-950/35 px-5 py-6 sm:px-7 sm:py-8">
        <h2 className="font-ctkp-display text-lg font-semibold text-amber-100/90">
          Những điểm lặp lại trong các lần luận
        </h2>
        <p className="mt-3 text-sm leading-relaxed text-stone-400">
          Cần thêm dữ liệu — lưu thêm ít nhất một lần nữa <span className="text-stone-300">cùng mốc sinh đã ghi</span>{" "}
          (có thể khác năm quan sát) để hệ thống đối chiếu dọc thời gian một cách an toàn.
        </p>
      </section>
    );
  }

  const ins = bundle.insights;

  return (
    <section className="rounded-2xl border border-amber-950/25 bg-stone-950/35 px-5 py-6 sm:px-7 sm:py-8">
      <h2 className="font-ctkp-display text-lg font-semibold text-amber-100/90">
        Những điểm lặp lại trong các lần luận
      </h2>
      <p className="mt-2 text-xs leading-relaxed text-stone-500">
        So sánh {ins.comparedReadingCount} bản lưu gần nhất trong nhóm cùng ngày/giờ/giới tính đã ghi — chỉ mô tả tín
        hiệu có trong dữ liệu, không thêm sự kiện.
      </p>
      <details
        className="mt-4 rounded-xl border border-stone-800/70 bg-black/20 px-4 py-3"
        onToggle={(e) => {
          const t = e.currentTarget;
          if (t.open) sendExpand(bundle);
        }}
      >
        <summary className="cursor-pointer text-sm font-medium text-amber-200/90">
          Xem chi tiết đối chiếu
        </summary>
        <div className="mt-3 border-t border-stone-800/50 pt-4">
          <InsightList title="Chủ đề lặp" items={ins.recurringThemes} />
          <InsightList title="Điểm mạnh lặp (theo archetype)" items={ins.recurringStrengths} />
          <InsightList title="Rủi ro cấu trúc lặp" items={ins.recurringRisks} />
          <InsightList title="Thay đổi trọng tâm / tín hiệu" items={ins.shiftingFocusAreas} />
          <InsightList title="Thời điểm & năm quan sát" items={ins.timingChanges} />
          <InsightList title="Lưu ý độ tin / giới hạn" items={ins.confidenceNotes} />
        </div>
      </details>
    </section>
  );
}
