"use client";

import { useEffect, useState, useCallback } from "react";
import {
  ShieldAlert, ShieldCheck, AlertTriangle, RefreshCw,
  CheckCircle2, XCircle, ChevronDown, ChevronUp,
  BadgeCheck, RotateCcw, Eye,
} from "lucide-react";
import Link from "next/link";
import type { ModerationStats, ModerationCar, ModerationIssue } from "@/lib/types";

const API = process.env.NEXT_PUBLIC_API_URL || "http://localhost:8000";

type Tab = "rejected" | "warnings";

function token() {
  return typeof window !== "undefined"
    ? sessionStorage.getItem("drivehub_admin_token") || ""
    : "";
}

async function apiFetch(path: string, opts: RequestInit = {}) {
  return fetch(`${API}${path}`, {
    ...opts,
    headers: { Authorization: `Bearer ${token()}`, "Content-Type": "application/json", ...opts.headers },
  });
}

// ── Issue row ─────────────────────────────────────────────────────────────────

function IssueChip({ issue, severity }: { issue: ModerationIssue; severity: "error" | "warning" }) {
  const color = severity === "error"
    ? "bg-red-50 border-red-200 text-red-700"
    : "bg-amber-50 border-amber-200 text-amber-700";
  return (
    <div className={`rounded-xl border p-3 ${color}`}>
      <div className="flex items-start justify-between gap-2 mb-1 min-w-0">
        <span className="text-[11px] font-black uppercase tracking-wider break-words min-w-0">{issue.field}</span>
        <span className={`text-[10px] font-bold px-1.5 py-0.5 rounded shrink-0 ${
          severity === "error" ? "bg-red-100 text-red-600" : "bg-amber-100 text-amber-600"
        }`}>
          {severity}
        </span>
      </div>
      <p className="text-xs font-semibold break-words">{issue.issue}</p>
      {issue.value && (
        <p className="text-[10px] opacity-60 mt-1 font-mono break-all">
          Value: {String(issue.value).slice(0, 80)}
        </p>
      )}
    </div>
  );
}

// ── Car accordion row ─────────────────────────────────────────────────────────

function CarRow({ car, onAction }: { car: ModerationCar; onAction: () => void }) {
  const [expanded, setExpanded]   = useState(false);
  const [loading, setLoading]     = useState<"whitelist" | "recheck" | null>(null);

  const mod = car.moderation;
  const hasErrors   = (mod?.errorCount   ?? 0) > 0;
  const hasWarnings = (mod?.warningCount ?? 0) > 0;

  async function handleWhitelist() {
    setLoading("whitelist");
    try {
      await apiFetch(`/api/moderation/whitelist/${car.id}`, { method: "POST" });
      onAction();
    } finally { setLoading(null); }
  }

  async function handleRecheck() {
    setLoading("recheck");
    try {
      await apiFetch(`/api/moderation/recheck/${car.id}`, { method: "POST" });
      onAction();
    } finally { setLoading(null); }
  }

  return (
    <div className="bg-white rounded-2xl border border-gray-100 overflow-hidden shadow-sm min-w-0">
      <div className="flex flex-col gap-3 p-4 sm:flex-row sm:items-center sm:gap-4 hover:bg-gray-50 transition-colors">
        <button
          type="button"
          onClick={() => setExpanded(!expanded)}
          className="flex min-w-0 flex-1 items-center gap-3 text-left"
          aria-expanded={expanded}
        >
          <div className={`w-8 h-8 rounded-full flex items-center justify-center shrink-0 ${
            hasErrors ? "bg-red-100" : "bg-amber-100"
          }`}>
            {hasErrors
              ? <XCircle className="w-4 h-4 text-red-500" />
              : <AlertTriangle className="w-4 h-4 text-amber-500" />
            }
          </div>

          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-2 flex-wrap">
              <span className="font-bold text-gray-900 text-sm break-words">{car.brand} {car.name}</span>
              {hasErrors && (
                <span className="text-[10px] font-black px-2 py-0.5 rounded-full bg-red-100 text-red-600 shrink-0">
                  {mod.errorCount} error{mod.errorCount !== 1 ? "s" : ""}
                </span>
              )}
              {hasWarnings && (
                <span className="text-[10px] font-black px-2 py-0.5 rounded-full bg-amber-100 text-amber-600 shrink-0">
                  {mod.warningCount} warning{mod.warningCount !== 1 ? "s" : ""}
                </span>
              )}
            </div>
            <p className="text-xs text-gray-400 mt-0.5 break-words">
              Score: {Math.round((mod?.score ?? 0) * 100)}% · {mod?.checkedAt ? new Date(mod.checkedAt).toLocaleDateString() : "—"}
            </p>
          </div>

          {expanded
            ? <ChevronUp className="w-4 h-4 text-gray-400 shrink-0" />
            : <ChevronDown className="w-4 h-4 text-gray-400 shrink-0" />
          }
        </button>

        <div className="flex flex-wrap items-center gap-2 shrink-0 sm:justify-end">
          <button
            type="button"
            onClick={handleRecheck}
            disabled={!!loading}
            className="inline-flex min-h-11 items-center justify-center text-[11px] font-bold px-3 py-2 rounded-lg border border-gray-200 bg-white hover:bg-gray-50 text-gray-600 transition-colors disabled:opacity-40"
          >
            {loading === "recheck" ? <RotateCcw className="w-3 h-3 animate-spin" /> : "Re-check"}
          </button>
          {hasErrors && (
            <button
              type="button"
              onClick={handleWhitelist}
              disabled={!!loading}
              className="inline-flex min-h-11 items-center justify-center text-[11px] font-bold px-3 py-2 rounded-lg bg-green-600 text-white hover:bg-green-700 transition-colors disabled:opacity-40"
            >
              {loading === "whitelist" ? "…" : "Approve"}
            </button>
          )}
        </div>
      </div>

      {expanded && (
        <div className="border-t border-gray-100 p-4 bg-gray-50/50">
          {(mod?.errors?.length ?? 0) > 0 && (
            <div className="mb-4">
              <p className="text-xs font-black uppercase tracking-wider text-red-600 mb-2">Errors — will block publishing</p>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
                {mod.errors.map((e, i) => (
                  <IssueChip key={i} issue={e} severity="error" />
                ))}
              </div>
            </div>
          )}
          {(mod?.warnings?.length ?? 0) > 0 && (
            <div>
              <p className="text-xs font-black uppercase tracking-wider text-amber-600 mb-2">Warnings — published with flags</p>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
                {mod.warnings.map((w, i) => (
                  <IssueChip key={i} issue={w} severity="warning" />
                ))}
              </div>
            </div>
          )}
          {car.slug && (
            <div className="mt-3 flex justify-end">
              <Link
                href={`/cars/${car.slug}`}
                target="_blank"
                className="flex items-center gap-1.5 text-xs font-semibold text-blue-600 hover:underline"
              >
                <Eye className="w-3.5 h-3.5" />
                View car page
              </Link>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

// ── Page ──────────────────────────────────────────────────────────────────────

export default function ModerationPage() {
  const [stats,    setStats]    = useState<ModerationStats | null>(null);
  const [rejected, setRejected] = useState<ModerationCar[]>([]);
  const [warnings, setWarnings] = useState<ModerationCar[]>([]);
  const [tab,      setTab]      = useState<Tab>("rejected");
  const [loading,  setLoading]  = useState(true);
  const [running,  setRunning]  = useState(false);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const [statsRes, rejRes, warnRes] = await Promise.all([
        apiFetch("/api/moderation/stats"),
        apiFetch("/api/moderation/rejections?limit=100"),
        apiFetch("/api/moderation/warnings?limit=100"),
      ]);
      if (statsRes.ok) setStats(await statsRes.json());
      if (rejRes.ok)  { const d = await rejRes.json();  setRejected(d.cars || []); }
      if (warnRes.ok) { const d = await warnRes.json(); setWarnings(d.cars || []); }
    } finally {
      setLoading(false);
    }
  }, []);

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

  async function runModeration() {
    setRunning(true);
    try {
      await apiFetch("/api/moderation/run", { method: "POST" });
      await load();
    } finally {
      setRunning(false);
    }
  }

  const passedPct  = stats ? Math.round((stats.passed / (stats.total || 1)) * 100) : 0;
  const activeList = tab === "rejected" ? rejected : warnings;

  const STAT_CARDS = [
    { label: "Total Cars",    value: stats?.total   ?? "—", color: "bg-gray-50  border-gray-200" },
    { label: "Passed",        value: stats ? `${stats.passed} (${passedPct}%)` : "—", color: "bg-green-50 border-green-200 text-green-700" },
    { label: "Rejected",      value: stats?.rejected ?? "—", color: stats?.rejected ? "bg-red-50 border-red-200 text-red-700" : "bg-gray-50 border-gray-200" },
    { label: "With Warnings", value: stats?.withWarnings ?? "—", color: stats?.withWarnings ? "bg-amber-50 border-amber-200 text-amber-700" : "bg-gray-50 border-gray-200" },
  ];

  return (
    <div className="p-4 sm:p-6 max-w-5xl mx-auto min-w-0 overflow-x-hidden pb-[calc(1.5rem+env(safe-area-inset-bottom,0px))]">
      {/* Header */}
      <div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between mb-6 min-w-0">
        <div className="min-w-0">
          <h1 className="text-xl sm:text-2xl font-black text-gray-900 flex items-center gap-2 min-w-0">
            <ShieldAlert className="w-6 h-6 text-red-500 shrink-0" />
            <span className="break-words">AI Moderation Layer</span>
          </h1>
          <p className="text-gray-500 text-sm mt-1 break-words">
            Validates price, fuel type, transmission, mileage, images, colors and SEO fields before publishing.
          </p>
        </div>
        <button
          type="button"
          onClick={runModeration}
          disabled={running || loading}
          className="inline-flex w-full sm:w-auto min-h-11 shrink-0 items-center justify-center gap-1.5 px-4 py-2.5 rounded-xl bg-blue-600 text-white text-sm font-semibold hover:bg-blue-700 transition-colors disabled:opacity-50"
        >
          <RefreshCw className={`w-4 h-4 shrink-0 ${running ? "animate-spin" : ""}`} />
          Run Moderation
        </button>
      </div>

      {/* Rules legend */}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 mb-6 min-w-0">
        {[
          { label: "Price Range",    detail: "₹2L – ₹10Cr",      color: "bg-blue-50 border-blue-200 text-blue-700" },
          { label: "Fuel & Gearbox", detail: "Known types only",  color: "bg-purple-50 border-purple-200 text-purple-700" },
          { label: "Mileage",        detail: "5–70 km/l for ICE", color: "bg-green-50 border-green-200 text-green-700" },
          { label: "SEO & Images",   detail: "Name, brand, URLs", color: "bg-amber-50 border-amber-200 text-amber-700" },
        ].map(({ label, detail, color }) => (
          <div key={label} className={`rounded-2xl border p-3 min-w-0 ${color}`}>
            <p className="font-black text-sm break-words">{label}</p>
            <p className="text-xs opacity-70 mt-0.5 break-words">{detail}</p>
          </div>
        ))}
      </div>

      {/* KPI cards */}
      {loading ? (
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 sm:gap-4 mb-6">
          {Array.from({ length: 4 }).map((_, i) => (
            <div key={i} className="h-24 rounded-2xl bg-gray-100 animate-pulse" />
          ))}
        </div>
      ) : (
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 sm:gap-4 mb-6 min-w-0">
          {STAT_CARDS.map(({ label, value, color }) => (
            <div key={label} className={`rounded-2xl border p-3 sm:p-5 min-w-0 ${color}`}>
              <p className="text-xl sm:text-2xl font-black break-words">{value}</p>
              <p className="text-xs font-semibold opacity-70 mt-0.5 break-words">{label}</p>
            </div>
          ))}
        </div>
      )}

      {/* Tabs */}
      <div className="flex flex-wrap gap-2 mb-4 min-w-0">
        {([
          { key: "rejected", label: `Rejected (${rejected.length})`, icon: XCircle,       active: "bg-red-600 text-white",   inactive: "bg-white text-gray-600 border border-gray-200" },
          { key: "warnings", label: `Warnings (${warnings.length})`, icon: AlertTriangle, active: "bg-amber-500 text-white", inactive: "bg-white text-gray-600 border border-gray-200" },
        ] as const).map(({ key, label, icon: Icon, active, inactive }) => (
          <button
            type="button"
            key={key}
            onClick={() => setTab(key)}
            className={`inline-flex min-h-11 items-center justify-center gap-1.5 px-4 py-2.5 rounded-xl text-sm font-bold transition-colors ${tab === key ? active : inactive}`}
          >
            <Icon className="w-4 h-4 shrink-0" />
            <span className="whitespace-nowrap">{label}</span>
          </button>
        ))}
      </div>

      {/* List */}
      {loading ? (
        <div className="space-y-3">
          {Array.from({ length: 5 }).map((_, i) => (
            <div key={i} className="h-16 rounded-2xl bg-gray-100 animate-pulse" />
          ))}
        </div>
      ) : activeList.length === 0 ? (
        <div className="text-center py-16 px-4 bg-white rounded-2xl border border-gray-100 min-w-0">
          {tab === "rejected"
            ? <ShieldCheck className="w-12 h-12 text-green-400 mx-auto mb-3" />
            : <BadgeCheck   className="w-12 h-12 text-blue-400 mx-auto mb-3" />
          }
          <p className="font-bold text-gray-700 break-words">
            {tab === "rejected" ? "No rejected cars" : "No cars with warnings"}
          </p>
          <p className="text-sm text-gray-400 mt-1 break-words">Run moderation to evaluate all cars</p>
        </div>
      ) : (
        <div className="space-y-3 min-w-0">
          {activeList.map((car) => (
            <CarRow key={car.id} car={car} onAction={load} />
          ))}
        </div>
      )}

      <p className="text-xs text-gray-400 mt-6 text-center break-words px-2">
        Moderation runs daily at 11:00 UTC after enrichment and confidence checks.
        Rejected cars are never served to users. Admins can approve exceptions.
      </p>
    </div>
  );
}
