"use client";
import { useState } from "react";
import { BookOpen, Copy, KeyRound, Plus } from "lucide-react";
import { Badge, Button, Card, Checkbox, Empty, Field, Input, PageHeader, Sheet, api, useAction, useUI } from "@/components/ui";
import { ago, useApi } from "@/components/hooks";

export default function ApiKeysPage() {
  const keys = useApi<{ data: any[]; scopes: string[] }>("/api-keys");
  const [open, setOpen] = useState(false);
  const [name, setName] = useState("");
  const [scopes, setScopes] = useState<string[]>(["read:contacts", "write:leads"]);
  const [created, setCreated] = useState<string | null>(null);
  const { busy, run } = useAction();
  const { push, confirm } = useUI();
  return (
    <>
      <PageHeader title="API keys" subtitle="Scoped keys for server-to-server access, Zapier, Make, n8n and your own apps"
        actions={<><a href="/docs/api" target="_blank" rel="noreferrer"><Button icon={<BookOpen className="h-3.5 w-3.5" />}>API reference</Button></a><Button variant="primary" icon={<Plus className="h-3.5 w-3.5" />} onClick={() => { setOpen(true); setCreated(null); setName(""); }}>Create key</Button></>} />
      <Card bodyClass="p-0">
        {!keys.data?.data.length ? <Empty title="No API keys" icon={<KeyRound className="h-5 w-5" />} /> : (
          <table className="table-mac">
            <thead><tr><th>Name</th><th>Key</th><th>Scopes</th><th>Last used</th><th>Status</th><th /></tr></thead>
            <tbody>{keys.data.data.map((k) => (
              <tr key={k.id}><td className="font-medium">{k.name}</td><td className="font-mono text-[12px] text-ink-3">{k.prefix}…</td><td className="max-w-[340px]"><div className="flex flex-wrap gap-1">{k.scopes.map((s: string) => <Badge key={s} tone={s.startsWith("write") || s === "admin" ? "amber" : "gray"}>{s}</Badge>)}</div></td><td className="text-ink-3">{ago(k.lastUsedAt)}</td>
                <td>{k.revokedAt ? <Badge>Revoked</Badge> : <Badge tone="green" dot>Active</Badge>}</td>
                <td className="text-right">{!k.revokedAt && <button className="text-[12px] text-bad hover:underline" onClick={async () => { if (await confirm({ title: `Revoke “${k.name}”?`, body: "Apps using this key stop working immediately.", danger: true, confirmLabel: "Revoke" })) { await api(`/api-keys/${k.id}`, { method: "DELETE" }); keys.reload(); } }}>Revoke</button>}</td></tr>
            ))}</tbody>
          </table>
        )}
      </Card>
      <Card className="mt-4" title="Quick start">
        <pre className="overflow-x-auto rounded-[8px] bg-sunken p-3 font-mono text-[11.5px]">{`curl -X POST ${typeof window !== "undefined" ? location.origin : ""}/api/v1/leads \\
  -H "Authorization: Bearer tp_live_…" \\
  -H "Content-Type: application/json" \\
  -H "Idempotency-Key: $(uuidgen)" \\
  -d '{"name":"Rahim Hossain","phone":"01712345678","project":"Gulshan Heights",
       "attribution":{"channel":"website","utm_source":"google","gclid":"Cj0K…"}}'`}</pre>
        <p className="mt-2 text-[12px] text-ink-3">Zapier / Make / n8n: authenticate with an API key (test call GET /api/v1/me), subscribe triggers via POST /api/v1/webhooks and unsubscribe with DELETE /api/v1/webhooks/{"{id}"}.</p>
      </Card>
      <Sheet open={open} onClose={() => setOpen(false)} width={560} title="Create API key" footer={created ? <Button variant="primary" onClick={() => setOpen(false)}>Done</Button> : <><Button onClick={() => setOpen(false)}>Cancel</Button><Button variant="primary" loading={busy} onClick={() => run(async () => { const r = await api("/api-keys", { body: { name, scopes } }); setCreated(r.data.key); keys.reload(); })}>Create</Button></>}>
        {created ? (
          <div className="space-y-2"><p className="text-[13px]">Copy this key now — it won’t be shown again.</p><div className="flex gap-2"><Input readOnly className="font-mono text-[12px]" value={created} /><Button icon={<Copy className="h-3.5 w-3.5" />} onClick={() => { navigator.clipboard.writeText(created); push("ok", "Copied"); }}>Copy</Button></div></div>
        ) : (
          <div className="space-y-3">
            <Field label="Name"><Input value={name} onChange={(e) => setName(e.target.value)} placeholder="Website lead form" /></Field>
            <Field label="Scopes" hint="A key limited to read:contacts cannot write"><div className="grid grid-cols-2 gap-1.5 rounded-[9px] border border-line p-2.5">{keys.data?.scopes.map((s) => <Checkbox key={s} checked={scopes.includes(s)} onChange={(v) => setScopes(v ? [...scopes, s] : scopes.filter((x) => x !== s))} label={<code className="text-[11.5px]">{s}</code>} />)}</div></Field>
          </div>
        )}
      </Sheet>
    </>
  );
}
