"use client";

/**
 * Admin → Compliance
 * ──────────────────
 * Platform compliance dashboard:
 *  - Headline metrics (total brands, healthcare-mode coverage, DPA
 *    status counts, platform compliance score, retention summary)
 *  - Per-brand status table with traffic-light score + flags
 *  - Right-to-deletion form (typed-confirmation guarded)
 *  - Right-to-access export form
 *  - ComplianceEvent log feed + CSV export
 */

import { useCallback, useEffect, useState } from "react";
import {
  ShieldCheck, AlertTriangle, Loader2, Trash2, Download, FileText,
  RefreshCw, Lock,
} from "lucide-react";

interface Overview {
  summary: {
    totalBrands: number;
    healthcareEnabled: number;
    likelyHealthcareTotal: number;
    dpaSignedCount: number;
    dpaCounts: Array<{ status: string; count: number }>;
    platformScore: number;
    platformRetentionDays: number;
    purgeCountNext30Days: number;
    nextScheduledPurge: string;
  };
  perBrand: Array<{
    id: string; name: string; domain: string; industry: string | null;
    likelyHealthcare: boolean; healthcareMode: boolean;
    retentionDays: number; retentionOverride: boolean;
    dpaStatus: string; dpaSignedAt: string | null;
    score: number;
    flags: { healthcareModeMissing: boolean; dpaMissing: boolean };
  }>;
  recentEvents: Array<{
    id: string; action: string; brandId: string | null; identifier: string | null;
    details: unknown; requestedBy: string; timestamp: string;
  }>;
}

function scoreColor(s: number): string {
  if (s >= 80) return "bg-emerald-500 text-white";
  if (s >= 50) return "bg-amber-500 text-white";
  return "bg-red-500 text-white";
}

function formatDate(s: string | null): string {
  if (!s) return "—";
  try { return new Date(s).toLocaleString(undefined, { month: "short", day: "numeric", year: "numeric", hour: "2-digit", minute: "2-digit" }); } catch { return s; }
}

export default function AdminCompliancePage() {
  const [data, setData] = useState<Overview | null>(null);
  const [loading, setLoading] = useState(true);
  const [toast, setToast] = useState<string | null>(null);
  const show = (msg: string) => { setToast(msg); setTimeout(() => setToast(null), 2500); };

  // Right-to-deletion + export form state
  const [identifier, setIdentifier] = useState("");
  const [confirmDelete, setConfirmDelete] = useState("");
  const [busyAction, setBusyAction] = useState<"delete" | "export" | null>(null);

  const refresh = useCallback(async () => {
    setLoading(true);
    const res = await fetch("/api/admin/compliance/overview");
    if (res.ok) setData(await res.json());
    setLoading(false);
  }, []);

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

  async function runDelete() {
    if (!identifier.trim() || confirmDelete !== "DELETE") return;
    setBusyAction("delete");
    try {
      const res = await fetch("/api/admin/compliance/delete-user-data", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ identifier: identifier.trim() }),
      });
      if (res.ok) {
        const d = await res.json();
        const totals = d.deleted as { events: number; sessions: number; conversions: number; siteEvents: number };
        show(`Deleted: ${totals.events} events · ${totals.sessions} sessions · ${totals.conversions} conversions · ${totals.siteEvents} signals`);
        setIdentifier("");
        setConfirmDelete("");
        await refresh();
      } else {
        const d = await res.json().catch(() => ({}));
        show(d.error || "Delete failed");
      }
    } finally {
      setBusyAction(null);
    }
  }

  async function runExport() {
    if (!identifier.trim()) return;
    setBusyAction("export");
    try {
      const res = await fetch("/api/admin/compliance/export-user-data", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ identifier: identifier.trim() }),
      });
      if (res.ok) {
        const blob = await res.blob();
        const url = URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url;
        a.download = `user-data-${identifier.trim().replace(/[^a-z0-9._-]/gi, "_")}.json`;
        a.click();
        URL.revokeObjectURL(url);
        show("Export downloaded");
        await refresh();
      } else {
        show("Export failed");
      }
    } finally {
      setBusyAction(null);
    }
  }

  if (loading || !data) {
    return (
      <div className="flex items-center justify-center py-24">
        <Loader2 className="w-5 h-5 text-slate-400 animate-spin" />
      </div>
    );
  }

  const { summary, perBrand, recentEvents } = data;

  return (
    <div className="space-y-6">
      <div className="flex items-start justify-between">
        <div>
          <h1 className="text-2xl font-bold text-slate-900 flex items-center gap-2">
            <ShieldCheck className="w-5 h-5 text-slate-700" /> Compliance
          </h1>
          <p className="text-slate-500 text-sm mt-1">
            Platform compliance status, retention policy, and right-to-deletion / export tooling.
          </p>
        </div>
        <button
          onClick={refresh}
          className="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold rounded-lg border border-slate-200 bg-white text-slate-600 hover:bg-slate-50"
        >
          <RefreshCw className="w-3 h-3" /> Refresh
        </button>
      </div>

      {/* Hero gauge + 3 supporting stat cards */}
      {/* ── Cookie usage banner ──
          The Site Tag is cookieless by construction (sessionStorage +
          localStorage only — neither is a cookie, neither is sent over
          HTTP, neither is covered by ePrivacy / cookie-consent regs).
          We surface this on the compliance page because brands fielding
          GDPR / CCPA / cookie-banner audits need it documented in the
          compliance posture, not buried in product copy. */}
      <div className="rounded-xl border border-emerald-200 bg-emerald-50/60 px-4 py-3 flex items-start gap-3">
        <span className="w-7 h-7 rounded-lg bg-emerald-100 text-emerald-700 flex items-center justify-center shrink-0 text-base">
          🍪
        </span>
        <div className="min-w-0 flex-1">
          <p className="text-sm font-bold text-emerald-900">
            Cookie usage: <span className="text-emerald-700">None — cookieless tracking</span>
          </p>
          <p className="text-[11px] text-emerald-800/80 mt-0.5 leading-relaxed">
            The meSEO Site Tag sets zero cookies on visitors&apos; browsers. Session and visitor identifiers live in <code className="font-mono text-[10px] bg-white/70 px-1 py-0.5 rounded">sessionStorage</code> / <code className="font-mono text-[10px] bg-white/70 px-1 py-0.5 rounded">localStorage</code> — neither is transmitted with HTTP requests and neither falls under ePrivacy / GDPR cookie-consent rules. Brands using only the Site Tag for analytics do not need a cookie consent banner for that tracking surface.
          </p>
        </div>
        <span className="text-[10px] font-bold uppercase tracking-widest px-2 py-0.5 rounded-full bg-emerald-100 text-emerald-700 border border-emerald-200 shrink-0">
          Compliance advantage
        </span>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-4 gap-3">
        {/* Gauge — lg:col-span-1; hero metric. */}
        <div className="bg-white border border-slate-100 rounded-xl shadow-sm p-5 flex items-center gap-5">
          <ComplianceGauge score={summary.platformScore} />
          <div className="min-w-0">
            <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-500">Platform compliance</p>
            <p className="text-xs text-slate-500 mt-1 leading-relaxed">
              Average across {summary.totalBrands} brand{summary.totalBrands !== 1 ? "s" : ""}.
            </p>
          </div>
        </div>
        <div className="bg-white border border-slate-100 rounded-xl shadow-sm p-4">
          <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-500">Healthcare mode</p>
          <p className="text-3xl font-semibold text-slate-800 tabular-nums leading-tight mt-1">
            {summary.healthcareEnabled}
            <span className="text-base text-slate-400 font-normal"> / {summary.likelyHealthcareTotal}</span>
          </p>
          <p className="text-[11px] text-slate-500 mt-1">enabled / suspected healthcare</p>
        </div>
        <div className="bg-white border border-slate-100 rounded-xl shadow-sm p-4">
          <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-500">DPA signed</p>
          <p className="text-3xl font-semibold text-slate-800 tabular-nums leading-tight mt-1">{summary.dpaSignedCount}</p>
          <div className="flex items-center gap-1 mt-1 flex-wrap">
            {summary.dpaCounts.map((d) => (
              <span key={d.status} className="text-[9px] font-bold uppercase tracking-wider px-1.5 py-0.5 rounded bg-slate-100 text-slate-600">
                {d.status}: {d.count}
              </span>
            ))}
          </div>
        </div>
        <div className="bg-white border border-slate-100 rounded-xl shadow-sm p-4">
          <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-500">Retention</p>
          <p className="text-3xl font-semibold text-slate-800 tabular-nums leading-tight mt-1">
            {summary.platformRetentionDays}
            <span className="text-base text-slate-400 font-normal"> d</span>
          </p>
          <p className="text-[11px] text-slate-500 mt-1">{summary.purgeCountNext30Days.toLocaleString()} signals due in 30d</p>
          <p className="text-[10px] text-slate-400 mt-0.5">Cron: {summary.nextScheduledPurge}</p>
        </div>
      </div>

      {/* Per-brand table */}
      <div className="bg-white border border-slate-200 rounded-xl overflow-hidden">
        <div className="px-4 py-3 border-b border-slate-100 flex items-center gap-2">
          <ShieldCheck className="w-4 h-4 text-brand-600" />
          <h2 className="font-bold text-slate-800 text-sm">Brand compliance status</h2>
          <span className="ml-auto text-xs text-slate-500">{perBrand.length} brands</span>
        </div>
        {perBrand.length === 0 ? (
          <div className="p-12 text-center text-slate-400 text-sm">No brands yet.</div>
        ) : (
          <table className="w-full text-sm">
            <thead className="bg-slate-50 border-b border-slate-200">
              <tr className="text-[10px] font-bold text-slate-500 uppercase tracking-wider">
                <th className="text-left px-4 py-3">Brand</th>
                <th className="text-center px-3 py-3">Healthcare mode</th>
                <th className="text-center px-3 py-3">Retention</th>
                <th className="text-center px-3 py-3">DPA</th>
                <th className="text-right px-3 py-3">Score</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100">
              {perBrand.map((b) => (
                <tr key={b.id}>
                  <td className="px-4 py-2.5">
                    <p className="text-xs font-semibold text-slate-800 truncate max-w-[260px]">{b.name}</p>
                    <p className="text-[10px] text-slate-500 font-mono truncate max-w-[260px]">{b.domain}</p>
                  </td>
                  <td className="px-3 py-2.5 text-center">
                    {b.likelyHealthcare ? (
                      b.healthcareMode ? (
                        <span className="text-[10px] font-bold uppercase tracking-wider px-1.5 py-0.5 rounded bg-emerald-50 text-emerald-700 border border-emerald-200">Enabled</span>
                      ) : (
                        <span className="inline-flex items-center gap-1 text-[10px] font-bold uppercase tracking-wider px-1.5 py-0.5 rounded bg-red-50 text-red-700 border border-red-200">
                          <AlertTriangle className="w-3 h-3" /> Required
                        </span>
                      )
                    ) : (
                      <span className="text-[10px] text-slate-400">N/A</span>
                    )}
                  </td>
                  <td className="px-3 py-2.5 text-center text-xs text-slate-700">
                    {b.retentionDays}d
                    {b.retentionOverride && <span className="ml-1 text-[10px] text-slate-400">(override)</span>}
                  </td>
                  <td className="px-3 py-2.5 text-center">
                    <span className={`text-[10px] font-bold uppercase tracking-wider px-1.5 py-0.5 rounded border ${
                      b.dpaStatus === "signed" ? "bg-emerald-50 text-emerald-700 border-emerald-200"
                      : b.dpaStatus === "pending" ? "bg-amber-50 text-amber-700 border-amber-200"
                      : "bg-slate-100 text-slate-600 border-slate-200"
                    }`}>
                      {b.dpaStatus}
                    </span>
                  </td>
                  <td className="px-3 py-2.5 text-right">
                    <span className={`text-[10px] font-bold tabular-nums px-2 py-0.5 rounded-full ${scoreColor(b.score)}`}>
                      {b.score}
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      {/* Right-to-deletion / export */}
      <div className="bg-white border border-slate-200 rounded-xl overflow-hidden">
        <div className="px-4 py-3 border-b border-slate-100 flex items-center gap-2">
          <Lock className="w-4 h-4 text-brand-600" />
          <h2 className="font-bold text-slate-800 text-sm">Subject access requests</h2>
        </div>
        <div className="px-4 py-4 space-y-3">
          <div>
            <label className="block text-[11px] font-semibold text-slate-600 mb-1">Identifier (email or sessionId)</label>
            <input
              value={identifier}
              onChange={(e) => setIdentifier(e.target.value)}
              placeholder="someone@example.com or session_abc123"
              className="w-full px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-500/40"
            />
          </div>
          <div className="flex items-center gap-3">
            <button
              onClick={runExport}
              disabled={!identifier.trim() || busyAction !== null}
              className="inline-flex items-center gap-1.5 px-4 py-2 text-xs font-semibold rounded-lg border border-slate-200 bg-white text-slate-700 hover:bg-slate-50 disabled:opacity-50"
            >
              {busyAction === "export" ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Download className="w-3.5 h-3.5" />}
              Export user data (Article 15)
            </button>
            <span className="text-[11px] text-slate-400">
              Returns a JSON dump of every event/session/conversion the platform holds for this identifier.
            </span>
          </div>
          <div className="border-t border-slate-100 pt-3">
            <p className="text-[11px] font-semibold text-red-700 mb-2 flex items-center gap-1.5">
              <Trash2 className="w-3 h-3" /> Right to deletion (Article 17)
            </p>
            <p className="text-[11px] text-slate-500 mb-2">
              Type <span className="font-mono font-bold text-slate-700">DELETE</span> to confirm. Wipes every TrackedEvent,
              TrackedSession, SiteConversion, and SiteEvent for the identifier. Logged immutably.
            </p>
            <div className="flex items-center gap-2">
              <input
                value={confirmDelete}
                onChange={(e) => setConfirmDelete(e.target.value)}
                placeholder="Type DELETE"
                className="px-3 py-2 text-sm border border-red-200 rounded-lg font-mono w-32 focus:outline-none focus:ring-2 focus:ring-red-500/40"
              />
              <button
                onClick={runDelete}
                disabled={!identifier.trim() || confirmDelete !== "DELETE" || busyAction !== null}
                className="inline-flex items-center gap-1.5 px-4 py-2 text-xs font-semibold rounded-lg bg-red-600 text-white hover:bg-red-700 disabled:opacity-40"
              >
                {busyAction === "delete" ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Trash2 className="w-3.5 h-3.5" />}
                Delete all data
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* Compliance event log */}
      <div className="bg-white border border-slate-200 rounded-xl overflow-hidden">
        <div className="px-4 py-3 border-b border-slate-100 flex items-center gap-2">
          <FileText className="w-4 h-4 text-brand-600" />
          <h2 className="font-bold text-slate-800 text-sm">Compliance event log</h2>
          <a
            href="/api/admin/compliance/events?format=csv"
            className="ml-auto inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold rounded-lg border border-slate-200 bg-white text-slate-600 hover:bg-slate-50"
          >
            <Download className="w-3 h-3" /> Export CSV
          </a>
        </div>
        {recentEvents.length === 0 ? (
          <div className="p-12 text-center text-slate-400 text-sm">No compliance events yet.</div>
        ) : (
          <ul className="divide-y divide-slate-100">
            {recentEvents.map((e) => (
              <li key={e.id} className="px-4 py-2.5 flex items-center gap-3">
                <span className="text-[10px] tabular-nums text-slate-400 w-32 shrink-0">{formatDate(e.timestamp)}</span>
                <span className="text-[10px] font-bold uppercase tracking-wider px-1.5 py-0.5 rounded bg-slate-100 text-slate-700 shrink-0 min-w-[140px] text-center">
                  {e.action}
                </span>
                {e.identifier && (
                  <span className="text-xs text-slate-700 font-mono truncate">{e.identifier}</span>
                )}
                {e.brandId && (
                  <span className="text-[10px] text-slate-400 font-mono truncate">brand: {e.brandId}</span>
                )}
                <span className="ml-auto text-[10px] text-slate-400 font-mono">{e.requestedBy.slice(0, 12)}…</span>
              </li>
            ))}
          </ul>
        )}
      </div>

      {toast && (
        <div className="fixed top-4 right-4 z-50 px-4 py-2 rounded-lg bg-slate-900 text-white text-xs font-semibold shadow-lg max-w-md">
          {toast}
        </div>
      )}
    </div>
  );
}

// ─── Hero gauge — circular progress with score in center ─────────

function ComplianceGauge({ score }: { score: number }) {
  const size = 96;
  const stroke = 8;
  const radius = (size - stroke) / 2;
  const C = 2 * Math.PI * radius;
  const offset = C - (score / 100) * C;
  const strokeColor = score >= 80 ? "#10B981" : score >= 50 ? "#F59E0B" : "#F43F5E";
  const textColor = score >= 80 ? "text-emerald-600" : score >= 50 ? "text-amber-600" : "text-rose-600";
  return (
    <div className="relative shrink-0" style={{ width: size, height: size }}>
      <svg width={size} height={size} className="-rotate-90">
        <circle
          cx={size / 2} cy={size / 2} r={radius}
          stroke="#F1F5F9" strokeWidth={stroke} fill="none"
        />
        <circle
          cx={size / 2} cy={size / 2} r={radius}
          stroke={strokeColor} strokeWidth={stroke} fill="none"
          strokeLinecap="round"
          strokeDasharray={C}
          strokeDashoffset={offset}
          style={{ transition: "stroke-dashoffset 600ms ease-out" }}
        />
      </svg>
      <span className={`absolute inset-0 flex items-center justify-center text-2xl font-semibold tabular-nums ${textColor}`}>
        {score}
      </span>
    </div>
  );
}
