import { useState } from "react";
import { FileCheck, Trash2, Pencil, Plus, Download, ClipboardList } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Badge } from "@/components/ui/badge";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import { cn } from "@/lib/utils";
import type { ProcessingEntry } from "@/types/api";
import {
  useListEntries,
  useCreateEntry,
  useUpdateEntry,
  useDeleteEntry,
  useClassifyEntry,
  useGdprAccess,
  useGdprErase,
  downloadPdf,
} from "@/api/compliance";

// ─── Constants ─────────────────────────────────────────────────────────────────

const LEGAL_BASIS_OPTIONS = [
  { value: "consent", label: "Consentement" },
  { value: "contract", label: "Contrat" },
  { value: "legal_obligation", label: "Obligation légale" },
  { value: "vital_interests", label: "Intérêts vitaux" },
  { value: "public_task", label: "Mission d'intérêt public" },
  { value: "legitimate_interest", label: "Intérêt légitime" },
];

const DATA_CATEGORIES_OPTIONS = [
  "Email",
  "Téléphone",
  "Nom",
  "Adresse",
  "INSEE/SSN",
  "IBAN",
  "Carte bancaire",
  "Biométrique",
  "Santé",
];

const AI_ACT_QUESTIONS = [
  { key: "q1", label: "Décisions autonomes affectant des droits légaux des personnes ?" },
  { key: "q2", label: "Traitement de données biométriques ou émotionnelles ?" },
  { key: "q3", label: "Décisions critiques (santé, justice, emploi) ?" },
  { key: "q4", label: "Données sensibles à caractère spécial (Art. 9 RGPD) ?" },
  { key: "q5", label: "Transparence sur l'utilisation de l'IA requise par la loi ?" },
];

// ─── Helpers ───────────────────────────────────────────────────────────────────

function scoreRisk(answers: Record<string, boolean>): ProcessingEntry["risk_level"] {
  const count = Object.values(answers).filter(Boolean).length;
  if (count === 0) return "minimal";
  if (count <= 2) return "limited";
  if (count <= 4) return "high";
  return "forbidden";
}

function RiskBadge({ level }: { level: ProcessingEntry["risk_level"] }) {
  const map: Record<string, { label: string; className: string }> = {
    forbidden: { label: "Interdit", className: "bg-red-100 text-red-800" },
    high: { label: "Haut risque", className: "bg-orange-100 text-orange-800" },
    limited: { label: "Risque limité", className: "bg-yellow-100 text-yellow-800" },
    minimal: { label: "Risque minimal", className: "bg-green-100 text-green-800" },
    "": { label: "Non classifié", className: "bg-gray-100 text-gray-600" },
  };
  const { label, className } = map[level ?? ""] ?? map[""];
  return (
    <span className={cn("inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium", className)}>
      {label}
    </span>
  );
}

function legalBasisLabel(value: string): string {
  return LEGAL_BASIS_OPTIONS.find((o) => o.value === value)?.label ?? value;
}

// ─── Tab 1 — Registre ──────────────────────────────────────────────────────────

type EntryFormData = {
  use_case_name: string;
  legal_basis: string;
  purpose: string;
  data_categories: string[];
  recipients: string[];
  processors: string[];
  retention_period: string;
  security_measures: string;
  controller_name: string;
};

const EMPTY_FORM: EntryFormData = {
  use_case_name: "",
  legal_basis: "consent",
  purpose: "",
  data_categories: [],
  recipients: [],
  processors: [],
  retention_period: "",
  security_measures: "",
  controller_name: "",
};

function entryToForm(e: ProcessingEntry): EntryFormData {
  return {
    use_case_name: e.use_case_name,
    legal_basis: e.legal_basis,
    purpose: e.purpose,
    data_categories: e.data_categories ?? [],
    recipients: e.recipients ?? [],
    processors: e.processors ?? [],
    retention_period: e.retention_period,
    security_measures: e.security_measures ?? "",
    controller_name: e.controller_name ?? "",
  };
}

function RegistreTab() {
  const { data: entries = [], isLoading } = useListEntries();
  const createEntry = useCreateEntry();
  const updateEntry = useUpdateEntry();
  const deleteEntry = useDeleteEntry();

  const [dialogOpen, setDialogOpen] = useState(false);
  const [editId, setEditId] = useState<string | null>(null);
  const [form, setForm] = useState<EntryFormData>(EMPTY_FORM);
  const [deleteId, setDeleteId] = useState<string | null>(null);
  const [saving, setSaving] = useState(false);

  function openCreate() {
    setEditId(null);
    setForm(EMPTY_FORM);
    setDialogOpen(true);
  }

  function openEdit(e: ProcessingEntry) {
    setEditId(e.id);
    setForm(entryToForm(e));
    setDialogOpen(true);
  }

  function toggleCategory(cat: string) {
    setForm((f) => ({
      ...f,
      data_categories: f.data_categories.includes(cat)
        ? f.data_categories.filter((c) => c !== cat)
        : [...f.data_categories, cat],
    }));
  }

  async function handleSave() {
    setSaving(true);
    try {
      if (editId) {
        await updateEntry.mutateAsync({ id: editId, ...form });
      } else {
        await createEntry.mutateAsync(form);
      }
      setDialogOpen(false);
    } finally {
      setSaving(false);
    }
  }

  async function handleDelete() {
    if (!deleteId) return;
    await deleteEntry.mutateAsync(deleteId);
    setDeleteId(null);
  }

  return (
    <div className="space-y-4">
      <div className="flex justify-between items-center">
        <p className="text-sm text-muted-foreground">
          {entries.length} traitement{entries.length !== 1 ? "s" : ""} enregistré{entries.length !== 1 ? "s" : ""}
        </p>
        <Button size="sm" onClick={openCreate}>
          <Plus className="h-4 w-4 mr-2" />
          Nouveau traitement
        </Button>
      </div>

      {isLoading ? (
        <p className="text-sm text-muted-foreground">Chargement…</p>
      ) : entries.length === 0 ? (
        <div className="rounded-lg border border-dashed p-8 text-center text-muted-foreground">
          Aucun traitement enregistré. Commencez par en créer un.
        </div>
      ) : (
        <div className="rounded-md border overflow-hidden">
          <table className="w-full text-sm">
            <thead className="bg-muted/50">
              <tr>
                <th className="text-left px-4 py-2.5 font-medium">Cas d'usage</th>
                <th className="text-left px-4 py-2.5 font-medium">Base légale</th>
                <th className="text-left px-4 py-2.5 font-medium">Risque AI Act</th>
                <th className="px-4 py-2.5" />
              </tr>
            </thead>
            <tbody className="divide-y">
              {entries.map((e) => (
                <tr key={e.id} className="hover:bg-muted/30">
                  <td className="px-4 py-2.5 font-medium">{e.use_case_name}</td>
                  <td className="px-4 py-2.5 text-muted-foreground">{legalBasisLabel(e.legal_basis)}</td>
                  <td className="px-4 py-2.5">
                    <RiskBadge level={e.risk_level} />
                  </td>
                  <td className="px-4 py-2.5">
                    <div className="flex items-center justify-end gap-2">
                      <Button variant="ghost" size="icon" onClick={() => openEdit(e)} title="Modifier">
                        <Pencil className="h-3.5 w-3.5" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="icon"
                        className="text-destructive hover:text-destructive"
                        onClick={() => setDeleteId(e.id)}
                        title="Supprimer"
                      >
                        <Trash2 className="h-3.5 w-3.5" />
                      </Button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {/* Create/Edit dialog */}
      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
        <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{editId ? "Modifier le traitement" : "Nouveau traitement"}</DialogTitle>
          </DialogHeader>
          <div className="space-y-4 py-2">
            <div className="grid grid-cols-2 gap-4">
              <div className="col-span-2 space-y-1">
                <Label>Nom du cas d'usage *</Label>
                <Input
                  value={form.use_case_name}
                  onChange={(e) => setForm((f) => ({ ...f, use_case_name: e.target.value }))}
                  placeholder="ex. Assistance RH avec IA"
                />
              </div>
              <div className="space-y-1">
                <Label>Base légale *</Label>
                <Select value={form.legal_basis} onValueChange={(v) => setForm((f) => ({ ...f, legal_basis: v }))}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {LEGAL_BASIS_OPTIONS.map((o) => (
                      <SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-1">
                <Label>Durée de conservation *</Label>
                <Input
                  value={form.retention_period}
                  onChange={(e) => setForm((f) => ({ ...f, retention_period: e.target.value }))}
                  placeholder="ex. 3 ans après fin de contrat"
                />
              </div>
              <div className="col-span-2 space-y-1">
                <Label>Finalité *</Label>
                <Textarea
                  value={form.purpose}
                  onChange={(e) => setForm((f) => ({ ...f, purpose: e.target.value }))}
                  placeholder="Décrivez l'objectif du traitement…"
                  rows={2}
                />
              </div>
              <div className="col-span-2 space-y-2">
                <Label>Catégories de données</Label>
                <div className="flex flex-wrap gap-2">
                  {DATA_CATEGORIES_OPTIONS.map((cat) => (
                    <button
                      key={cat}
                      type="button"
                      onClick={() => toggleCategory(cat)}
                      className={cn(
                        "rounded-full border px-3 py-1 text-xs font-medium transition-colors",
                        form.data_categories.includes(cat)
                          ? "bg-primary text-primary-foreground border-primary"
                          : "border-border text-muted-foreground hover:bg-muted"
                      )}
                    >
                      {cat}
                    </button>
                  ))}
                </div>
              </div>
              <div className="space-y-1">
                <Label>Responsable de traitement</Label>
                <Input
                  value={form.controller_name}
                  onChange={(e) => setForm((f) => ({ ...f, controller_name: e.target.value }))}
                  placeholder="ex. Acme Corp DPO"
                />
              </div>
              <div className="space-y-1">
                <Label>Destinataires (séparés par virgule)</Label>
                <Input
                  value={form.recipients.join(", ")}
                  onChange={(e) =>
                    setForm((f) => ({
                      ...f,
                      recipients: e.target.value.split(",").map((s) => s.trim()).filter(Boolean),
                    }))
                  }
                  placeholder="ex. Service RH, Direction"
                />
              </div>
              <div className="space-y-1">
                <Label>Sous-traitants LLM (séparés par virgule)</Label>
                <Input
                  value={form.processors.join(", ")}
                  onChange={(e) =>
                    setForm((f) => ({
                      ...f,
                      processors: e.target.value.split(",").map((s) => s.trim()).filter(Boolean),
                    }))
                  }
                  placeholder="ex. OpenAI, Anthropic"
                />
              </div>
              <div className="col-span-2 space-y-1">
                <Label>Mesures de sécurité</Label>
                <Textarea
                  value={form.security_measures}
                  onChange={(e) => setForm((f) => ({ ...f, security_measures: e.target.value }))}
                  placeholder="Décrivez les mesures techniques et organisationnelles…"
                  rows={2}
                />
              </div>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setDialogOpen(false)}>Annuler</Button>
            <Button onClick={handleSave} disabled={saving || !form.use_case_name || !form.purpose || !form.retention_period}>
              {saving ? "Enregistrement…" : editId ? "Mettre à jour" : "Créer"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Delete confirm */}
      <AlertDialog open={!!deleteId} onOpenChange={(open) => !open && setDeleteId(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Supprimer ce traitement ?</AlertDialogTitle>
            <AlertDialogDescription>
              Cette action est irréversible. Le traitement sera désactivé dans le registre.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Annuler</AlertDialogCancel>
            <AlertDialogAction onClick={handleDelete} className="bg-destructive text-destructive-foreground hover:bg-destructive/90">
              Supprimer
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}

// ─── Tab 2 — Questionnaire AI Act ──────────────────────────────────────────────

function AiActTab() {
  const { data: entries = [] } = useListEntries();
  const classifyEntry = useClassifyEntry();

  const [selectedId, setSelectedId] = useState("");
  const [answers, setAnswers] = useState<Record<string, boolean>>({});
  const [saving, setSaving] = useState(false);
  const [saved, setSaved] = useState(false);

  const localRisk = scoreRisk(answers);

  function toggleAnswer(key: string) {
    setAnswers((a) => ({ ...a, [key]: !a[key] }));
    setSaved(false);
  }

  async function handleClassify() {
    if (!selectedId) return;
    setSaving(true);
    try {
      await classifyEntry.mutateAsync({ id: selectedId, answers });
      setSaved(true);
    } finally {
      setSaving(false);
    }
  }

  const riskDescriptions: Record<string, string> = {
    forbidden: "Ce système est interdit par l'AI Act (Art. 5). Il ne peut pas être déployé.",
    high: "Ce système est à haut risque (Annexe III). Des exigences strictes s'appliquent (documentation, évaluation de conformité, surveillance humaine).",
    limited: "Ce système présente un risque limité. Des obligations de transparence s'appliquent.",
    minimal: "Ce système présente un risque minimal. Aucune obligation spécifique AI Act.",
    "": "Répondez aux questions pour calculer le niveau de risque.",
  };

  return (
    <div className="space-y-6 max-w-2xl">
      <div className="space-y-2">
        <Label>Cas d'usage à classifier</Label>
        <Select value={selectedId} onValueChange={(v) => { setSelectedId(v); setSaved(false); }}>
          <SelectTrigger>
            <SelectValue placeholder="Sélectionner un traitement…" />
          </SelectTrigger>
          <SelectContent>
            {entries.map((e) => (
              <SelectItem key={e.id} value={e.id}>{e.use_case_name}</SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      <div className="rounded-lg border p-4 space-y-4">
        {AI_ACT_QUESTIONS.map((q) => (
          <div key={q.key} className="flex items-center justify-between gap-4">
            <Label className="text-sm font-normal leading-snug">{q.label}</Label>
            <Switch
              checked={!!answers[q.key]}
              onCheckedChange={() => toggleAnswer(q.key)}
            />
          </div>
        ))}
      </div>

      <div className={cn(
        "rounded-lg border p-4 space-y-2",
        localRisk === "forbidden" && "border-red-200 bg-red-50",
        localRisk === "high" && "border-orange-200 bg-orange-50",
        localRisk === "limited" && "border-yellow-200 bg-yellow-50",
        localRisk === "minimal" && "border-green-200 bg-green-50",
        localRisk === "" && "border-gray-200 bg-gray-50",
      )}>
        <div className="flex items-center gap-3">
          <span className="text-sm font-medium">Niveau de risque calculé :</span>
          <RiskBadge level={localRisk} />
        </div>
        <p className="text-sm text-muted-foreground">{riskDescriptions[localRisk]}</p>
      </div>

      <div className="flex items-center gap-3">
        <Button onClick={handleClassify} disabled={!selectedId || saving}>
          {saving ? "Enregistrement…" : "Enregistrer la classification"}
        </Button>
        {saved && <span className="text-sm text-green-600 font-medium">Classification enregistrée ✓</span>}
      </div>
    </div>
  );
}

// ─── Tab 3 — Rapports ──────────────────────────────────────────────────────────

function RapportsTab() {
  const { data: entries = [] } = useListEntries();
  const [dpiaId, setDpiaId] = useState("");
  const [csvStart, setCsvStart] = useState("");
  const [csvEnd, setCsvEnd] = useState("");
  const [downloading, setDownloading] = useState<string | null>(null);

  async function dl(key: string, url: string, filename: string) {
    setDownloading(key);
    try {
      await downloadPdf(url, filename);
    } catch (err) {
      console.error("Download failed", err);
    } finally {
      setDownloading(null);
    }
  }

  const today = new Date().toISOString().slice(0, 10);

  return (
    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
      {/* Article 30 */}
      <div className="rounded-lg border p-5 space-y-3">
        <div className="flex items-center gap-2">
          <FileCheck className="h-5 w-5 text-primary" />
          <h3 className="font-semibold text-sm">Registre RGPD Article 30</h3>
        </div>
        <p className="text-xs text-muted-foreground">
          Registre des activités de traitement conforme à l'Art. 30 du RGPD. Requis pour tout organisme &gt; 250 personnes.
        </p>
        <div className="flex gap-2">
          <Button
            size="sm"
            onClick={() => dl("art30-pdf", "/v1/admin/compliance/report/article30?format=pdf", `article30_${today}.pdf`)}
            disabled={downloading === "art30-pdf"}
          >
            <Download className="h-3.5 w-3.5 mr-1.5" />
            {downloading === "art30-pdf" ? "…" : "Télécharger PDF"}
          </Button>
          <Button
            size="sm"
            variant="outline"
            onClick={() => dl("art30-json", "/v1/admin/compliance/report/article30?format=json", `article30_${today}.json`)}
            disabled={downloading === "art30-json"}
          >
            Exporter JSON
          </Button>
        </div>
      </div>

      {/* AI Act */}
      <div className="rounded-lg border p-5 space-y-3">
        <div className="flex items-center gap-2">
          <ClipboardList className="h-5 w-5 text-primary" />
          <h3 className="font-semibold text-sm">Rapport AI Act</h3>
        </div>
        <p className="text-xs text-muted-foreground">
          Synthèse de la classification des risques AI Act pour tous vos cas d'usage IA.
        </p>
        <div className="flex gap-2">
          <Button
            size="sm"
            onClick={() => dl("aiact-pdf", "/v1/admin/compliance/report/aiact?format=pdf", `aiact_${today}.pdf`)}
            disabled={downloading === "aiact-pdf"}
          >
            <Download className="h-3.5 w-3.5 mr-1.5" />
            {downloading === "aiact-pdf" ? "…" : "Télécharger PDF"}
          </Button>
          <Button
            size="sm"
            variant="outline"
            onClick={() => dl("aiact-json", "/v1/admin/compliance/report/aiact?format=json", `aiact_${today}.json`)}
            disabled={downloading === "aiact-json"}
          >
            Exporter JSON
          </Button>
        </div>
      </div>

      {/* DPIA */}
      <div className="rounded-lg border p-5 space-y-3">
        <div className="flex items-center gap-2">
          <FileCheck className="h-5 w-5 text-primary" />
          <h3 className="font-semibold text-sm">Template DPIA (Art. 35)</h3>
        </div>
        <p className="text-xs text-muted-foreground">
          Analyse d'Impact relative à la Protection des Données pour les traitements à haut risque.
        </p>
        <div className="flex gap-2 items-center">
          <Select value={dpiaId} onValueChange={setDpiaId}>
            <SelectTrigger className="h-8 text-xs flex-1">
              <SelectValue placeholder="Choisir un traitement…" />
            </SelectTrigger>
            <SelectContent>
              {entries.map((e) => (
                <SelectItem key={e.id} value={e.id}>{e.use_case_name}</SelectItem>
              ))}
            </SelectContent>
          </Select>
          <Button
            size="sm"
            disabled={!dpiaId || downloading === "dpia"}
            onClick={() => dl("dpia", `/v1/admin/compliance/dpia/${dpiaId}?format=pdf`, `dpia_${today}.pdf`)}
          >
            <Download className="h-3.5 w-3.5 mr-1.5" />
            {downloading === "dpia" ? "…" : "Générer"}
          </Button>
        </div>
      </div>

      {/* CSV Export */}
      <div className="rounded-lg border p-5 space-y-3">
        <div className="flex items-center gap-2">
          <Download className="h-5 w-5 text-primary" />
          <h3 className="font-semibold text-sm">Export Logs CSV</h3>
        </div>
        <p className="text-xs text-muted-foreground">
          Export des journaux d'audit au format CSV pour analyse ou archivage réglementaire.
        </p>
        <div className="flex gap-2 flex-wrap items-end">
          <div className="space-y-1">
            <Label className="text-xs">Début</Label>
            <Input type="date" value={csvStart} onChange={(e) => setCsvStart(e.target.value)} className="h-8 text-xs w-36" />
          </div>
          <div className="space-y-1">
            <Label className="text-xs">Fin</Label>
            <Input type="date" value={csvEnd} onChange={(e) => setCsvEnd(e.target.value)} className="h-8 text-xs w-36" />
          </div>
          <Button
            size="sm"
            disabled={downloading === "csv"}
            onClick={() => {
              const params = new URLSearchParams({ format: "csv" });
              if (csvStart) params.set("start", csvStart);
              if (csvEnd) params.set("end", csvEnd);
              dl("csv", `/v1/admin/compliance/export/logs?${params}`, `audit_logs_${today}.csv`);
            }}
          >
            <Download className="h-3.5 w-3.5 mr-1.5" />
            {downloading === "csv" ? "…" : "Exporter CSV"}
          </Button>
        </div>
      </div>
    </div>
  );
}

// ─── Tab 4 — RGPD (Art. 15 / Art. 17) ─────────────────────────────────────────

function RgpdTab() {
  // Art. 15
  const [accessUserId, setAccessUserId] = useState("");
  const [fetchUserId, setFetchUserId] = useState("");
  const { data: accessData, isLoading: accessLoading } = useGdprAccess(fetchUserId, !!fetchUserId);

  // Art. 17
  const [eraseUserId, setEraseUserId] = useState("");
  const [eraseReason, setEraseReason] = useState("");
  const [eraseConfirmOpen, setEraseConfirmOpen] = useState(false);
  const [eraseResult, setEraseResult] = useState<{ records_deleted: number; user_id: string } | null>(null);
  const gdprErase = useGdprErase();

  async function handleErase() {
    const res = await gdprErase.mutateAsync({ userId: eraseUserId, reason: eraseReason });
    setEraseResult({ records_deleted: res.records_deleted, user_id: res.user_id });
    setEraseConfirmOpen(false);
  }

  return (
    <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
      {/* Art. 15 — Droit d'accès */}
      <div className="rounded-lg border p-5 space-y-4">
        <div>
          <h3 className="font-semibold text-sm">Art. 15 — Droit d'accès</h3>
          <p className="text-xs text-muted-foreground mt-0.5">
            Récupérez toutes les données traitées pour un utilisateur donné.
          </p>
        </div>
        <div className="flex gap-2">
          <Input
            value={accessUserId}
            onChange={(e) => setAccessUserId(e.target.value)}
            placeholder="Identifiant utilisateur"
            className="flex-1"
          />
          <Button
            size="sm"
            onClick={() => setFetchUserId(accessUserId)}
            disabled={!accessUserId}
          >
            Extraire
          </Button>
        </div>
        {accessLoading && <p className="text-sm text-muted-foreground">Chargement…</p>}
        {accessData && (
          <div className="space-y-2">
            <div className="flex items-center gap-2 text-sm">
              <Badge variant="secondary">{accessData.total} enregistrement{accessData.total !== 1 ? "s" : ""}</Badge>
              <span className="text-muted-foreground text-xs">
                généré le {new Date(accessData.generated_at).toLocaleString("fr-FR")}
              </span>
            </div>
            <pre className="rounded bg-muted p-3 text-xs overflow-auto max-h-60 whitespace-pre-wrap">
              {JSON.stringify(accessData.records.slice(0, 5), null, 2)}
              {accessData.records.length > 5 && `\n…et ${accessData.records.length - 5} autres enregistrements`}
            </pre>
          </div>
        )}
      </div>

      {/* Art. 17 — Droit à l'effacement */}
      <div className="rounded-lg border p-5 space-y-4">
        <div>
          <h3 className="font-semibold text-sm">Art. 17 — Droit à l'effacement</h3>
          <p className="text-xs text-muted-foreground mt-0.5">
            Désactivez le compte et enregistrez l'effacement dans le journal RGPD.
          </p>
        </div>
        <div className="space-y-2">
          <Input
            value={eraseUserId}
            onChange={(e) => setEraseUserId(e.target.value)}
            placeholder="Email ou identifiant utilisateur"
          />
          <Textarea
            value={eraseReason}
            onChange={(e) => setEraseReason(e.target.value)}
            placeholder="Motif de la demande d'effacement…"
            rows={2}
          />
        </div>
        <Button
          variant="destructive"
          size="sm"
          disabled={!eraseUserId || gdprErase.isPending}
          onClick={() => setEraseConfirmOpen(true)}
        >
          {gdprErase.isPending ? "Traitement…" : "Effacer les données"}
        </Button>

        {eraseResult && (
          <div className="rounded bg-green-50 border border-green-200 p-3 text-sm text-green-800">
            ✓ Données de <strong>{eraseResult.user_id}</strong> effacées —{" "}
            {eraseResult.records_deleted} enregistrement{eraseResult.records_deleted !== 1 ? "s" : ""} supprimé{eraseResult.records_deleted !== 1 ? "s" : ""}.
          </div>
        )}
      </div>

      {/* Erase confirm dialog */}
      <AlertDialog open={eraseConfirmOpen} onOpenChange={setEraseConfirmOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Confirmer l'effacement</AlertDialogTitle>
            <AlertDialogDescription>
              Vous êtes sur le point d'effacer les données de <strong>{eraseUserId}</strong>. Cette action sera
              journalisée conformément à l'Art. 17 du RGPD. Le compte sera désactivé immédiatement.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Annuler</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleErase}
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
            >
              Confirmer l'effacement
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}

// ─── Main Page ─────────────────────────────────────────────────────────────────

const TABS = [
  { id: "registre", label: "Registre des traitements" },
  { id: "aiact", label: "Questionnaire AI Act" },
  { id: "rapports", label: "Rapports" },
  { id: "rgpd", label: "RGPD (Art. 15 / 17)" },
] as const;

type TabId = (typeof TABS)[number]["id"];

export function CompliancePage() {
  const [activeTab, setActiveTab] = useState<TabId>("registre");

  return (
    <div className="p-6 space-y-6">
      <div>
        <h2 className="text-2xl font-bold tracking-tight">Conformité RGPD / AI Act</h2>
        <p className="text-muted-foreground text-sm mt-1">
          Gérez votre registre des traitements, classifiez vos systèmes d'IA et exercez les droits des personnes.
        </p>
      </div>

      {/* Tab bar */}
      <div className="border-b flex gap-1">
        {TABS.map((tab) => (
          <button
            key={tab.id}
            onClick={() => setActiveTab(tab.id)}
            className={cn(
              "px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors",
              activeTab === tab.id
                ? "border-primary text-primary"
                : "border-transparent text-muted-foreground hover:text-foreground"
            )}
          >
            {tab.label}
          </button>
        ))}
      </div>

      {/* Tab content */}
      {activeTab === "registre" && <RegistreTab />}
      {activeTab === "aiact" && <AiActTab />}
      {activeTab === "rapports" && <RapportsTab />}
      {activeTab === "rgpd" && <RgpdTab />}
    </div>
  );
}
