"use client";

/**
 * Compact Data Confidence badge + expandable breakdown.
 *
 * Renders as a pill next to the Site Tag Active / Detected-Plugins
 * badges on the Site Tag Analytics overview. Colour-coded 0-100
 * score (green >= 80, amber 60-79, rose < 60). Clicking expands
 * a panel showing each factor's score + recommendation.
 *
 * Self-fetches /api/site-tag/confidence so the host page doesn't
 * need to thread an extra prop through.
 */

import { useCallback, useEffect, useState } from "react";
import {
  Gauge, CheckCircle2, AlertTriangle, XCircle, ChevronDown, Info,
} from "lucide-react";

interface Factor {
  id: string;
  label: string;
  score: number;
  weight: number;
  detail: string;
  recommendation: string | null;
}

interface ConfidenceResponse {
  score: number;
  verdict: "Healthy" | "Degraded" | "Poor";
  factors: Factor[];
  recommendations: Array<{ factor: string; label: string; message: string }>;
}

function verdictClasses(verdict: "Healthy" | "Degraded" | "Poor" | null) {
  if (verdict === "Healthy")  return { bg: "bg-emerald-50", border: "border-emerald-200", text: "text-emerald-700", dot: "bg-emerald-500", Icon: CheckCircle2 };
  if (verdict === "Degraded") return { bg: "bg-amber-50",   border: "border-amber-200",   text: "text-amber-700",   dot: "bg-amber-500",   Icon: AlertTriangle };
  if (verdict === "Poor")     return { bg: "bg-rose-50",    border: "border-rose-200",    text: "text-rose-700",    dot: "bg-rose-500",    Icon: XCircle };
  return { bg: "bg-slate-100", border: "border-slate-200", text: "text-slate-500", dot: "bg-slate-400", Icon: Gauge };
}

function factorIconFor(score: number) {
  if (score >= 80) return { Icon: CheckCircle2, color: "text-emerald-600" };
  if (score >= 60) return { Icon: AlertTriangle, color: "text-amber-600" };
  return { Icon: XCircle, color: "text-rose-600" };
}

export function ConfidenceBadge({
  brandId, range,
}: {
  brandId: string;
  range: "1d" | "7d" | "30d" | "90d";
}) {
  const [data, setData] = useState<ConfidenceResponse | null>(null);
  const [loading, setLoading] = useState(true);
  const [failed, setFailed] = useState(false);
  const [expanded, setExpanded] = useState(false);

  const load = useCallback(() => {
    if (!brandId || failed) return;
    setLoading(true);
    fetch(`/api/site-tag/confidence?brandId=${encodeURIComponent(brandId)}&range=${range}`)
      .then((r) => r.ok ? r.json() : null)
      .then((d: ConfidenceResponse | null) => {
        if (d) setData(d);
        else setFailed(true);
      })
      .catch(() => setFailed(true))
      .finally(() => setLoading(false));
  }, [brandId, range, failed]);

  useEffect(() => { load(); }, [load]);

  if (loading && !data) {
    return (
      <span className="inline-flex items-center gap-1 text-[11px] font-semibold bg-slate-50 text-slate-500 border border-slate-200 rounded-full px-2.5 py-1">
        <Gauge className="w-3 h-3 animate-pulse" /> Confidence…
      </span>
    );
  }
  if (!data) return null;

  const v = verdictClasses(data.verdict);
  const Icon = v.Icon;

  return (
    <>
      <button
        onClick={() => setExpanded((x) => !x)}
        className={`inline-flex items-center gap-1.5 text-[11px] font-semibold rounded-full border px-2.5 py-1 transition-colors ${v.bg} ${v.border} ${v.text} hover:brightness-95`}
        title={`Data Confidence: ${data.score}% (${data.verdict}). Click to see the breakdown.`}
      >
        <Icon className="w-3 h-3" />
        Data Confidence: <span className="font-bold">{data.score}%</span>
        <ChevronDown className={`w-3 h-3 transition-transform ${expanded ? "rotate-180" : ""}`} />
      </button>

      {expanded && (
        <div className="w-full mt-2 rounded-xl border border-slate-200 bg-white overflow-hidden">
          <div className="px-4 py-3 border-b border-slate-100 flex items-center gap-2">
            <Gauge className={`w-4 h-4 ${v.text}`} />
            <h3 className="text-sm font-bold text-slate-900">Data Confidence breakdown</h3>
            <span className={`ml-auto text-[10px] font-bold uppercase tracking-widest px-2 py-0.5 rounded-full border ${v.bg} ${v.border} ${v.text}`}>
              {data.verdict}
            </span>
          </div>
          <div className="divide-y divide-slate-100">
            {data.factors.map((f) => {
              const { Icon: FIcon, color } = factorIconFor(f.score);
              return (
                <div key={f.id} className="px-4 py-3">
                  <div className="flex items-center gap-2">
                    <FIcon className={`w-3.5 h-3.5 ${color}`} />
                    <p className="text-xs font-bold text-slate-800">{f.label}</p>
                    <span className="ml-auto text-[10px] font-semibold text-slate-500 tabular-nums">
                      <span className={`font-bold ${color}`}>{Math.round(f.score)}%</span>
                      <span className="text-slate-400"> · weight {f.weight}%</span>
                    </span>
                  </div>
                  <p className="text-[11px] text-slate-500 mt-0.5 leading-relaxed">{f.detail}</p>
                  {f.recommendation && (
                    <p className="text-[11px] mt-1 leading-relaxed text-slate-700 bg-amber-50/60 border-l-2 border-amber-300 pl-2 py-1 rounded-sm">
                      <Info className="w-3 h-3 inline-block mr-1 -mt-0.5 text-amber-600" />
                      {f.recommendation}
                    </p>
                  )}
                </div>
              );
            })}
          </div>
        </div>
      )}
    </>
  );
}
