import { router, useForm } from '@inertiajs/react';
import { KeyRound, Plus } from 'lucide-react';
import { useState } from 'react';
import { CopyText } from '@/components/CopyText';
import { PageHeader } from '@/components/PageHeader';
import { SettingsNav } from '@/components/SettingsNav';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardBody, CardHeader } from '@/components/ui/card';
import { Dialog } from '@/components/ui/dialog';
import { Input, Select } from '@/components/ui/input';
import { Field } from '@/components/ui/label';
import { Table, Td, Th } from '@/components/ui/table';
import AppLayout from '@/layouts/AppLayout';
import { dateTime } from '@/lib/format';

type Token = { id: number; name: string; prefix: string; abilities: string[]; user: string | null; last_used_at: string | null; expires_at: string | null; revoked_at: string | null; created_at: string };

const ENDPOINTS: [string, string, string][] = [
    ['GET', '/contacts', 'Contacts (shared by all companies). ?search, ?updated_since, ?page, ?per_page'],
    ['GET', '/contacts/{id}', 'One contact'],
    ['GET', '/items', 'This company’s item library (no cost prices). ?search, ?type'],
    ['GET', '/items/{id}', 'One item'],
    ['GET', '/quotes', 'Quotes. ?status, ?contact_id, ?updated_since'],
    ['GET', '/quotes/{id}', 'One quote with its lines'],
    ['POST', '/quotes', 'Create a draft quote (write tokens). Never sends it.'],
    ['GET', '/events', 'Tracking events (opens, clicks, views, accept…). ?since, ?quote_id, ?event'],
];

/** Settings → API: company-scoped REST API tokens and a quick reference. */
export default function Api({ tokens, created, baseUrl, rateLimit }: { tokens: Token[]; created: string | null; baseUrl: string; rateLimit: number }) {
    const [adding, setAdding] = useState(false);
    const example = `curl -H "Authorization: Bearer ${created ?? 'sgq_…'}" \\\n  ${baseUrl}/quotes?status=accepted`;
    const draft = `curl -X POST ${baseUrl}/quotes \\
  -H "Authorization: Bearer sgq_…" -H "Content-Type: application/json" \\
  -d '{"title":"Website refresh","contact":{"name":"Sam Lee","email":"sam@example.com"},
       "lines":[{"heading":"Design","qty":1,"unit_price_cents":250000},{"item_code":"HOST-12"}]}'`;
    return (
        <AppLayout title="API">
            <PageHeader title="API" breadcrumbs={[{ label: 'Settings', href: '/settings/company' }, { label: 'API' }]}
                description="REST API tokens for this company. A token only sees this company’s quotes and items, and acts with your role’s permissions." />
            <SettingsNav />
            <div className="grid max-w-5xl grid-cols-[minmax(0,1fr)] gap-6">
                {created && (
                    <Card className="border border-amber-300 bg-amber-50 p-4" data-testid="api-token-created">
                        <p className="mb-2 flex items-center gap-2 text-sm font-medium text-amber-900"><KeyRound className="h-4 w-4" /> Your new token: copy it now, it won’t be shown again.</p>
                        <CopyText value={created} />
                    </Card>
                )}
                <Card>
                    <CardHeader title="Tokens" actions={<Button size="sm" onClick={() => setAdding(true)} data-testid="add-api-token"><Plus className="h-4 w-4" /> New token</Button>} />
                    {tokens.length === 0 ? <CardBody><p className="text-sm text-ink-muted">No tokens yet.</p></CardBody> : (
                        <Table>
                            <thead><tr><Th>Name</Th><Th>Access</Th><Th>Created by</Th><Th>Last used</Th><Th>Expires</Th><Th /></tr></thead>
                            <tbody>{tokens.map((t) => (
                                <tr key={t.id} className={t.revoked_at ? 'opacity-60' : ''} data-testid="api-token-row">
                                    <Td><div className="font-medium">{t.name}</div><code className="text-xs text-ink-muted">{t.prefix}…</code></Td>
                                    <Td>{t.abilities.includes('write') ? 'Read & create drafts' : 'Read only'}</Td>
                                    <Td className="text-sm">{t.user}<div className="text-xs text-ink-muted">{dateTime(t.created_at)}</div></Td>
                                    <Td className="text-sm">{t.last_used_at ? dateTime(t.last_used_at) : 'Never'}</Td>
                                    <Td className="text-sm">{t.expires_at ? dateTime(t.expires_at) : 'Never'}</Td>
                                    <Td className="text-right">{t.revoked_at ? <Badge className="bg-stone-100 text-stone-700">Revoked</Badge>
                                        : <Button size="sm" variant="secondary" onClick={() => confirm(`Revoke “${t.name}”? Anything using it stops working.`) && router.delete(`/settings/api/tokens/${t.id}`, { preserveScroll: true })}>Revoke</Button>}</Td>
                                </tr>
                            ))}</tbody>
                        </Table>
                    )}
                </Card>
                <Card>
                    <CardHeader title="Quick reference" description={`Base URL ${baseUrl} · JSON · ${rateLimit} requests per minute per token · times in UTC · money in cents.`} />
                    <CardBody className="grid gap-4 text-sm">
                        <Table>
                            <tbody>{ENDPOINTS.map(([m, path, desc]) => (
                                <tr key={m + path}><Td className="w-16"><Badge className={m === 'GET' ? 'bg-blue/10 text-[#0b56b0]' : 'bg-teal/10 text-[#05705f]'}>{m}</Badge></Td><Td><code className="text-xs">{path}</code></Td><Td className="text-ink-muted">{desc}</Td></tr>
                            ))}</tbody>
                        </Table>
                        <div><div className="mb-1 font-medium">Example</div><CopyText multiline value={example} /></div>
                        <div><div className="mb-1 font-medium">Create a draft quote</div><CopyText multiline value={draft} /></div>
                        <p className="text-xs text-ink-muted">Cost prices and margins are never returned. $ values follow the token creator’s role (hidden for roles that can’t see them).</p>
                    </CardBody>
                </Card>
            </div>
            <NewToken open={adding} onClose={() => setAdding(false)} />
        </AppLayout>
    );
}

function NewToken({ open, onClose }: { open: boolean; onClose: () => void }) {
    const f = useForm({ name: '', access: 'read', expires_days: '', password: '' });
    return (
        <Dialog open={open} onOpenChange={(o) => !o && onClose()} title="New API token">
            <form className="grid gap-3" onSubmit={(e) => { e.preventDefault(); f.transform((d) => ({ ...d, expires_days: d.expires_days ? Number(d.expires_days) : null })); f.post('/settings/api/tokens', { onSuccess: () => { f.reset(); onClose(); }, onFinish: () => f.setData('password', '') }); }}>
                <Field label="Name" htmlFor="tok-name" error={f.errors.name} hint="What uses it, e.g. Zapier or the website."><Input id="tok-name" value={f.data.name} onChange={(e) => f.setData('name', e.target.value)} /></Field>
                <Field label="Access" htmlFor="tok-access">
                    <Select id="tok-access" value={f.data.access} onChange={(e) => f.setData('access', e.target.value)}>
                        <option value="read">Read only</option><option value="write">Read and create draft quotes</option>
                    </Select>
                </Field>
                <Field label="Expires" htmlFor="tok-exp">
                    <Select id="tok-exp" value={f.data.expires_days} onChange={(e) => f.setData('expires_days', e.target.value)}>
                        <option value="">Never</option><option value="30">In 30 days</option><option value="90">In 90 days</option><option value="365">In a year</option>
                    </Select>
                </Field>
                <Field label="Your password" htmlFor="tok-pw" error={f.errors.password} hint="To confirm it’s you."><Input id="tok-pw" type="password" autoComplete="current-password" value={f.data.password} onChange={(e) => f.setData('password', e.target.value)} /></Field>
                <div className="flex justify-end gap-2"><Button type="button" variant="secondary" onClick={onClose}>Cancel</Button><Button disabled={f.processing} data-testid="create-api-token">Create token</Button></div>
            </form>
        </Dialog>
    );
}
