import { Head, Link, router } from '@inertiajs/react';
import {
    Building2,
    Contact as ContactIcon,
    Pencil,
    Plus,
    Search,
    Trash2,
    User,
} from 'lucide-react';
import { useState } from 'react';
import { ConfirmDialog } from '@/components/confirm-dialog';
import { EmptyState } from '@/components/empty-state';
import { Kpi } from '@/components/kpi';
import { PageHeader } from '@/components/page-header';
import { Pagination } from '@/components/pagination';
import type { Paginated } from '@/components/pagination';
import { StatusBadge } from '@/components/status-badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import { create, destroy, edit, index, show } from '@/routes/contacts';

type Row = {
    id: string;
    kind: string;
    kind_label: string;
    name: string;
    city: string | null;
    state: string | null;
    category: string | null;
    is_client: boolean;
};

type Option = { value: number | string; label: string };

type Props = {
    contacts: Paginated<Row>;
    filters: { search: string; kind: string; category: number | null };
    categories: Option[];
    kinds: Option[];
    stats: {
        total: number;
        individuals: number;
        organizations: number;
        this_month: number;
    };
};

const ALL = 'all';

export default function ContactsIndex({
    contacts,
    filters,
    categories,
    kinds,
    stats,
}: Props) {
    const [search, setSearch] = useState(filters.search ?? '');

    const applyFilters = (
        patch: Record<string, string | number | null | undefined>,
    ) => {
        const next = {
            search,
            kind: filters.kind || undefined,
            category: filters.category || undefined,
            ...patch,
        };
        router.get(index().url, next, { preserveState: true, replace: true });
    };

    return (
        <>
            <Head title="Contacts" />
            <div className="flex flex-col gap-6 p-4">
                <PageHeader
                    title="Contacts"
                    subtitle="People and organizations referenced across the firm."
                    action={
                        <Button asChild>
                            <Link href={create()}>
                                <Plus /> Add contact
                            </Link>
                        </Button>
                    }
                />

                <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
                    <Kpi label="Total contacts" value={stats.total} />
                    <Kpi label="Individuals" value={stats.individuals} />
                    <Kpi label="Organizations" value={stats.organizations} />
                    <Kpi label="Added this month" value={stats.this_month} />
                </div>

                <Card>
                    <CardContent className="flex flex-wrap items-end gap-3 py-4">
                        <form
                            className="flex-1"
                            onSubmit={(e) => {
                                e.preventDefault();
                                applyFilters({ search });
                            }}
                        >
                            <div className="relative">
                                <Search className="absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-muted-foreground" />
                                <Input
                                    className="pl-8"
                                    placeholder="Search by name…"
                                    value={search}
                                    onChange={(e) => setSearch(e.target.value)}
                                />
                            </div>
                        </form>
                        <Select
                            value={filters.kind || ALL}
                            onValueChange={(v) =>
                                applyFilters({
                                    kind: v === ALL ? undefined : v,
                                })
                            }
                        >
                            <SelectTrigger className="w-44">
                                <SelectValue placeholder="Kind" />
                            </SelectTrigger>
                            <SelectContent>
                                <SelectItem value={ALL}>All kinds</SelectItem>
                                {kinds.map((k) => (
                                    <SelectItem
                                        key={k.value}
                                        value={String(k.value)}
                                    >
                                        {k.label}
                                    </SelectItem>
                                ))}
                            </SelectContent>
                        </Select>
                        <Select
                            value={
                                filters.category
                                    ? String(filters.category)
                                    : ALL
                            }
                            onValueChange={(v) =>
                                applyFilters({
                                    category: v === ALL ? undefined : v,
                                })
                            }
                        >
                            <SelectTrigger className="w-52">
                                <SelectValue placeholder="Category" />
                            </SelectTrigger>
                            <SelectContent>
                                <SelectItem value={ALL}>
                                    All categories
                                </SelectItem>
                                {categories.map((c) => (
                                    <SelectItem
                                        key={c.value}
                                        value={String(c.value)}
                                    >
                                        {c.label}
                                    </SelectItem>
                                ))}
                            </SelectContent>
                        </Select>
                    </CardContent>
                </Card>

                <Card>
                    <CardContent className="p-0">
                        {contacts.data.length === 0 ? (
                            <EmptyState
                                icon={ContactIcon}
                                title="No contacts found"
                                description="Adjust your filters, or add the firm's first contact."
                                action={
                                    <Button asChild>
                                        <Link href={create()}>
                                            <Plus /> Add contact
                                        </Link>
                                    </Button>
                                }
                            />
                        ) : (
                            <>
                                <Table>
                                    <TableHeader>
                                        <TableRow>
                                            <TableHead>Name</TableHead>
                                            <TableHead>Kind</TableHead>
                                            <TableHead>Category</TableHead>
                                            <TableHead>Location</TableHead>
                                            <TableHead className="text-right">
                                                Actions
                                            </TableHead>
                                        </TableRow>
                                    </TableHeader>
                                    <TableBody>
                                        {contacts.data.map((row) => (
                                            <TableRow key={row.id}>
                                                <TableCell className="font-medium text-foreground">
                                                    <Link
                                                        href={show(row.id)}
                                                        className="flex items-center gap-2 hover:text-primary"
                                                    >
                                                        {row.kind ===
                                                        'organization' ? (
                                                            <Building2 className="size-4 text-muted-foreground" />
                                                        ) : (
                                                            <User className="size-4 text-muted-foreground" />
                                                        )}
                                                        {row.name}
                                                        {row.is_client && (
                                                            <StatusBadge tone="info">
                                                                Client
                                                            </StatusBadge>
                                                        )}
                                                    </Link>
                                                </TableCell>
                                                <TableCell>
                                                    {row.kind_label}
                                                </TableCell>
                                                <TableCell>
                                                    {row.category ?? '—'}
                                                </TableCell>
                                                <TableCell>
                                                    {[row.city, row.state]
                                                        .filter(Boolean)
                                                        .join(', ') || '—'}
                                                </TableCell>
                                                <TableCell className="text-right">
                                                    <div className="flex justify-end gap-1">
                                                        <Button
                                                            asChild
                                                            variant="ghost"
                                                            size="icon-sm"
                                                        >
                                                            <Link
                                                                href={edit(
                                                                    row.id,
                                                                )}
                                                            >
                                                                <Pencil />
                                                            </Link>
                                                        </Button>
                                                        <ConfirmDialog
                                                            title={`Delete ${row.name}?`}
                                                            description="This contact will be removed. This cannot be undone."
                                                            confirmLabel="Delete contact"
                                                            onConfirm={() =>
                                                                router.delete(
                                                                    destroy(
                                                                        row.id,
                                                                    ).url,
                                                                )
                                                            }
                                                            trigger={
                                                                <Button
                                                                    variant="ghost"
                                                                    size="icon-sm"
                                                                >
                                                                    <Trash2 />
                                                                </Button>
                                                            }
                                                        />
                                                    </div>
                                                </TableCell>
                                            </TableRow>
                                        ))}
                                    </TableBody>
                                </Table>
                                <Pagination page={contacts} />
                            </>
                        )}
                    </CardContent>
                </Card>
            </div>
        </>
    );
}
