"use client";
import { useState } from "react";
import { Download, RotateCcw, Search, ShieldAlert, Trash2 } from "lucide-react";
import { Badge, Button, Card, Empty, Input, PageHeader, api, useUI } from "@/components/ui";
import { ago, useApi, useDebounced } from "@/components/hooks";

export default function PrivacyPage() {
  const [q, setQ] = useState("");
  const dq = useDebounced(q);
  const found = useApi<{ data: any[] }>(dq.length >= 3 ? `/contacts?q=${encodeURIComponent(dq)}&limit=10` : null, [dq]);
  const dead = useApi<{ data: any[] }>("/jobs?status=dead");
  const { confirm, push } = useUI();
  return (
    <>
      <PageHeader title="Privacy & data" subtitle="Data-subject requests (access / deletion), consent records and the dead-letter queue" />
      <div className="space-y-4">
        <Card title="Data-subject request" subtitle="Bangladesh data protection, GDPR, Australian Privacy Act and US state laws (e.g. CCPA)">
          <div className="relative"><Search className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-ink-3" /><Input className="pl-8" placeholder="Find the person by phone, email or name" value={q} onChange={(e) => setQ(e.target.value)} /></div>
          <ul className="mt-3 divide-y divide-line/60">
            {found.data?.data.map((c) => (
              <li key={c.id} className="flex flex-wrap items-center gap-3 py-2.5">
                <div className="min-w-0 flex-1"><a href={`/contacts/${c.id}`} className="font-medium hover:text-brand">{c.name}</a><div className="text-[11.5px] text-ink-3">{[c.phones[0], c.emails[0]].filter(Boolean).join(" · ")}</div></div>
                <a href={`/api/v1/contacts/${c.id}/export`} target="_blank" rel="noreferrer"><Button size="sm" icon={<Download className="h-3.5 w-3.5" />}>Export all data</Button></a>
                <a href={`/api/v1/contacts/${c.id}/consent/export`}><Button size="sm">Consent history</Button></a>
                <Button size="sm" variant="danger" icon={<Trash2 className="h-3.5 w-3.5" />} onClick={async () => { if (await confirm({ title: `Erase ${c.name}?`, body: "Hard-deletes the contact and everything linked (deals, messages, events, consents, attribution, submissions) across all modules immediately. Logged in the audit trail.", danger: true, confirmLabel: "Erase permanently" })) { await api(`/contacts/${c.id}`, { method: "DELETE" }); push("ok", "Contact erased"); found.reload(); } }}>Erase</Button>
              </li>
            ))}
          </ul>
          {dq.length >= 3 && found.data && !found.data.data.length && <p className="py-4 text-center text-[12.5px] text-ink-3">No matching contact</p>}
        </Card>
        <Card title="Dead-letter queue" subtitle="Background jobs that exhausted their retries (syncs, sends, webhooks) — fix the cause and replay" bodyClass="p-0">
          {!dead.data?.data.length ? <Empty title="Queue is clean" icon={<ShieldAlert className="h-5 w-5" />} /> : (
            <table className="table-mac"><thead><tr><th>Job</th><th>Attempts</th><th>Last error</th><th>Updated</th><th /></tr></thead>
              <tbody>{dead.data.data.map((j) => <tr key={j.id}><td className="font-mono text-[12px]">{j.type}</td><td>{j.attempts}</td><td className="max-w-[360px] truncate text-[12px] text-bad">{j.lastError}</td><td className="text-ink-3">{ago(j.updatedAt)}</td><td><Button size="sm" icon={<RotateCcw className="h-3.5 w-3.5" />} onClick={async () => { await api(`/jobs/${j.id}/replay`, { method: "POST" }); push("ok", "Replayed"); dead.reload(); }}>Replay</Button></td></tr>)}</tbody></table>
          )}
        </Card>
        <Card title="Compliance controls in place">
          <ul className="grid gap-2 text-[12.5px] sm:grid-cols-2">
            {["Consent per channel with source & timestamp; opted-out contacts excluded from every send", "STOP / UNSUBSCRIBE / বন্ধ keywords opt out instantly", "US SMS requires explicit opt-in (TCPA)", "WhatsApp 24-hour window & approved-template enforcement", "Quiet hours & frequency caps in workspace timezone", "Hard bounces and spam complaints suppress email automatically", "PII hashed (SHA-256) before sending to ad platforms", "Tokens & secrets AES-256-GCM encrypted in the vault", "Full audit log retained 1 year", "Tenant isolation on every query + automated isolation tests"].map((t) => <li key={t} className="flex gap-2"><Badge tone="green">✓</Badge><span>{t}</span></li>)}
          </ul>
        </Card>
      </div>
    </>
  );
}
