import { Link, router } from '@inertiajs/react';
import { Download, Plus, Upload } from 'lucide-react';
import { useState } from 'react';
import { CsvImportDialog } from '@/components/CsvImportDialog';
import { PageHeader } from '@/components/PageHeader';
import { Pagination } from '@/components/Pagination';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/input';
import { Table, Td, Th } from '@/components/ui/table';
import AppLayout from '@/layouts/AppLayout';
import type { Paginated } from '@/types';

type Row = { id: number; name: string; company: string | null; email: string | null; phone: string | null; quotes_count: number; archived: boolean };

export default function ContactsIndex({ contacts, filters, canEdit }: {
    contacts: Paginated<Row>; filters: { q: string | null; archived: boolean }; canEdit: boolean;
}) {
    const [q, setQ] = useState(filters.q ?? '');
    const [importing, setImporting] = useState(false);
    const apply = (patch: Partial<{ q: string; archived: boolean }>) => {
        const next = { q, archived: filters.archived, ...patch };
        router.get('/contacts', Object.fromEntries(Object.entries({ q: next.q || null, archived: next.archived ? 1 : null }).filter(([, v]) => v)),
            { preserveState: true, replace: true });
    };

    return (
        <AppLayout title="Contacts">
            <PageHeader title="Contacts" description="Shared across Spin Design, Spin Virtual Solutions and Australian Travelmate."
                actions={<>
                    <Button variant="secondary" asChild><a href={`/contacts/export${filters.archived ? '?archived=1' : ''}`} data-testid="export-contacts"><Download className="h-4 w-4" /> Export CSV</a></Button>
                    {canEdit && <Button variant="secondary" onClick={() => setImporting(true)} data-testid="import-contacts"><Upload className="h-4 w-4" /> Import CSV</Button>}
                    {canEdit && <Button asChild data-testid="new-contact"><Link href="/contacts/create"><Plus className="h-4 w-4" /> New contact</Link></Button>}
                </>} />
            <CsvImportDialog open={importing} onOpenChange={setImporting} url="/contacts/import" reload="contacts"
                title="Import contacts" description="Upload a CSV exported from Quotient, Outlook, Google Contacts or a spreadsheet."
                updateLabel="Update contacts that already exist (matched by email)"
                help={<>Recognised columns: First Name, Last Name (or Name), Company, Email, Other Emails, Phone, Mobile, Address Line 1 / 2, Suburb, State,
                    Postcode, Country, Tags, Notes. Other columns are ignored. Up to 1,000 rows per file.{' '}
                    <a href="/contacts/export" className="link">Export your contacts</a> to see the format.</>} />
            <Card>
                <form className="flex flex-wrap items-center gap-3 border-b border-line p-4" onSubmit={(e) => { e.preventDefault(); apply({}); }}>
                    <Input aria-label="Search contacts" placeholder="Search name, email or company" value={q} onChange={(e) => setQ(e.target.value)} className="max-w-xs" />
                    <Button type="submit" variant="secondary">Search</Button>
                    <Checkbox label="Show archived" checked={filters.archived} onChange={(e) => apply({ archived: e.target.checked })} />
                </form>
                <Table data-testid="contacts-table">
                    <thead><tr><Th>Name</Th><Th>Company</Th><Th>Email</Th><Th>Phone</Th><Th className="text-right">Quotes</Th></tr></thead>
                    <tbody>
                        {contacts.data.map((c) => (
                            <tr key={c.id}>
                                <Td className="font-medium"><Link href={`/contacts/${c.id}/edit`} className="link">{c.name}</Link>{c.archived && <Badge className="ml-2 bg-stone-100 text-stone-700">Archived</Badge>}</Td>
                                <Td>{c.company ?? '—'}</Td>
                                <Td>{c.email ? <a href={`mailto:${c.email}`} className="link">{c.email}</a> : '—'}</Td>
                                <Td className="whitespace-nowrap">{c.phone ?? '—'}</Td>
                                <Td className="text-right tabular-nums">{c.quotes_count}</Td>
                            </tr>
                        ))}
                        {contacts.data.length === 0 && (
                            <tr><Td colSpan={5} className="py-10 text-center text-ink-muted">
                                {filters.q ? 'No contacts match your search.' : filters.archived ? 'No archived contacts.' : 'No contacts yet.'}
                                {canEdit && !filters.q && !filters.archived && <> <Link href="/contacts/create" className="link">Add your first contact</Link>.</>}
                            </Td></tr>
                        )}
                    </tbody>
                </Table>
                <Pagination page={contacts} />
            </Card>
        </AppLayout>
    );
}

