"use client";

import { useCallback, useEffect, useState } from "react";
import { BarChart3, RefreshCw, Loader2 } from "lucide-react";
import { isAbortError } from "@/lib/utils/is-abort-error";

interface Benchmark { metric: string; value: number; sampleSize: number }
interface Rate { type: string; total: number; implemented: number; improved: number; avgImpact: number }
interface IndustryOption { value: string; label: string; count: number; meetsThreshold: boolean }

export default function AdminIndustryPage() {
  const [industry, setIndustry] = useState("");
  const [industries, setIndustries] = useState<IndustryOption[]>([]);
  const [industriesLoading, setIndustriesLoading] = useState(true);
  const [benchmarks, setBenchmarks] = useState<Record<string, { value: number; sampleSize: number }>>({});
  const [rates, setRates] = useState<Rate[]>([]);
  const [loading, setLoading] = useState(false);
  const [computing, setComputing] = useState(false);
  const [minSample, setMinSample] = useState(5);

  useEffect(() => {
    fetch("/api/admin/industries")
      .then((r) => r.json())
      .then((d) => {
        const list: IndustryOption[] = d.industries ?? [];
        setIndustries(list);
        if (typeof d.minSample === "number") setMinSample(d.minSample);
        if (list.length > 0 && !industry) setIndustry(list[0].value);
      })
      .catch((err) => { if (!isAbortError(err)) console.error(err); })
      .finally(() => setIndustriesLoading(false));
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const load = useCallback(async () => {
    if (!industry) return;
    setLoading(true);
    const [bRes, rRes] = await Promise.all([
      fetch(`/api/benchmarks?industry=${encodeURIComponent(industry)}`),
      fetch(`/api/benchmarks/success-rates?industry=${encodeURIComponent(industry)}`),
    ]);
    if (bRes.ok) { const d = await bRes.json(); setBenchmarks(d.benchmarks ?? {}); }
    if (rRes.ok) { const d = await rRes.json(); setRates(d.rates ?? []); }
    setLoading(false);
  }, [industry]);
  useEffect(() => { load(); }, [load]);

  async function compute() {
    setComputing(true);
    await fetch("/api/admin/compute-benchmarks", { method: "POST" });
    await load();
    setComputing(false);
  }

  const bKeys = Object.keys(benchmarks);
  const selectedOption = industries.find((i) => i.value === industry);

  return (
    <div className="space-y-6 max-w-5xl">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold text-slate-900">Industry Data</h1>
        <div className="flex items-center gap-2">
          {industriesLoading ? (
            <div className="flex items-center gap-1.5 px-3 py-2 text-xs text-slate-400">
              <Loader2 className="w-3.5 h-3.5 animate-spin" /> Loading industries…
            </div>
          ) : (
            <select
              value={industry}
              onChange={(e) => setIndustry(e.target.value)}
              className="text-sm border border-slate-200 rounded-lg px-3 py-2 bg-white max-w-xs"
            >
              {industries.length === 0 && <option value="">No brand industry data</option>}
              {industries.map((ind) => (
                <option key={ind.value} value={ind.value}>
                  {ind.label} ({ind.count} brand{ind.count !== 1 ? "s" : ""}{ind.meetsThreshold ? "" : ` — need ${minSample}+`})
                </option>
              ))}
            </select>
          )}
          <button onClick={compute} disabled={computing || !industry} className="flex items-center gap-1.5 px-3 py-2 rounded-lg bg-brand-600 text-white text-xs font-semibold hover:bg-brand-700 disabled:opacity-50">
            {computing ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <RefreshCw className="w-3.5 h-3.5" />} Compute Now
          </button>
        </div>
      </div>

      {selectedOption && !selectedOption.meetsThreshold && (
        <div className="rounded-lg border border-amber-200 bg-amber-50 px-4 py-3 text-xs text-amber-700">
          <strong>{selectedOption.label}</strong> has {selectedOption.count} brand{selectedOption.count !== 1 ? "s" : ""} — need {minSample - selectedOption.count} more to compute benchmarks (minimum {minSample}).
        </div>
      )}

      {loading ? <div className="py-12 text-center"><Loader2 className="w-6 h-6 animate-spin text-slate-400 mx-auto" /></div> : (
        <>
          <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
            <div className="px-5 py-3 border-b border-slate-100 flex items-center gap-2"><BarChart3 className="w-4 h-4 text-brand-600" /><h2 className="font-bold text-slate-800 text-sm">Benchmarks ({bKeys.length} metrics)</h2></div>
            {bKeys.length === 0 ? <div className="px-5 py-8 text-center text-xs text-slate-400">No benchmarks for this industry yet. {selectedOption?.meetsThreshold ? 'Click "Compute Now" to generate.' : `Need ${minSample - (selectedOption?.count ?? 0)} more brands.`}</div> :
            <table className="w-full text-sm"><thead><tr className="border-b border-slate-100 bg-slate-50/80 text-[10px] font-bold uppercase tracking-widest text-slate-400"><th className="px-4 py-2 text-left">Metric</th><th className="px-4 py-2 text-right">Value</th><th className="px-4 py-2 text-right">Sample</th></tr></thead>
              <tbody>{bKeys.sort().map((k) => <tr key={k} className="border-b border-slate-50"><td className="px-4 py-2 text-slate-700 capitalize">{k.replace(/_/g, " ")}</td><td className="px-4 py-2 text-right font-bold tabular-nums">{benchmarks[k].value}</td><td className="px-4 py-2 text-right text-slate-500 tabular-nums">{benchmarks[k].sampleSize}</td></tr>)}</tbody></table>}
          </div>

          {rates.length > 0 && (
            <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
              <div className="px-5 py-3 border-b border-slate-100"><h2 className="font-bold text-slate-800 text-sm">Recommendation Success Rates</h2></div>
              <table className="w-full text-sm"><thead><tr className="border-b border-slate-100 bg-slate-50/80 text-[10px] font-bold uppercase tracking-widest text-slate-400"><th className="px-4 py-2 text-left">Type</th><th className="px-4 py-2 text-right">Total</th><th className="px-4 py-2 text-right">Implemented</th><th className="px-4 py-2 text-right">Improved</th><th className="px-4 py-2 text-right">Avg Impact</th></tr></thead>
                <tbody>{rates.map((r) => <tr key={r.type} className="border-b border-slate-50"><td className="px-4 py-2 text-slate-700 capitalize">{r.type.replace(/_/g, " ")}</td><td className="px-4 py-2 text-right tabular-nums">{r.total}</td><td className="px-4 py-2 text-right tabular-nums">{r.implemented}</td><td className="px-4 py-2 text-right font-bold text-green-600 tabular-nums">{r.improved}</td><td className="px-4 py-2 text-right font-bold tabular-nums">{r.avgImpact > 0 ? "+" : ""}{r.avgImpact}%</td></tr>)}</tbody></table>
            </div>
          )}
        </>
      )}
    </div>
  );
}

