import { Head, Link, router } from '@inertiajs/react';
import { Briefcase, Pencil, Plus, Trash2 } from 'lucide-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 {
    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/clients';

type Row = {
    id: string;
    client_number: string;
    name: string;
    kind_label: string;
    status: string;
    status_label: string;
    relationship_partner: string | null;
    kyc_completed: boolean;
};

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

type Props = {
    clients: Paginated<Row>;
    filters: { status: string; partner: number | null };
    partners: Option[];
    statuses: Option[];
    stats: { active: number; inactive: number; this_month: number };
};

const ALL = 'all';

export default function ClientsIndex({
    clients,
    filters,
    partners,
    statuses,
    stats,
}: Props) {
    const applyFilters = (
        patch: Record<string, string | number | undefined>,
    ) => {
        router.get(
            index().url,
            {
                status: filters.status || undefined,
                partner: filters.partner || undefined,
                ...patch,
            },
            { preserveState: true, replace: true },
        );
    };

    return (
        <>
            <Head title="Clients" />
            <div className="flex flex-col gap-6 p-4">
                <PageHeader
                    title="Clients"
                    subtitle="Firms and individuals the practice represents."
                    action={
                        <Button asChild>
                            <Link href={create()}>
                                <Plus /> New client
                            </Link>
                        </Button>
                    }
                />

                <div className="grid gap-4 sm:grid-cols-3">
                    <Kpi label="Active clients" value={stats.active} />
                    <Kpi label="Inactive" value={stats.inactive} />
                    <Kpi label="New this month" value={stats.this_month} />
                </div>

                <Card>
                    <CardContent className="flex flex-wrap items-end gap-3 py-4">
                        <Select
                            value={filters.status || ALL}
                            onValueChange={(v) =>
                                applyFilters({
                                    status: v === ALL ? undefined : v,
                                })
                            }
                        >
                            <SelectTrigger className="w-44">
                                <SelectValue placeholder="Status" />
                            </SelectTrigger>
                            <SelectContent>
                                <SelectItem value={ALL}>
                                    All statuses
                                </SelectItem>
                                {statuses.map((s) => (
                                    <SelectItem
                                        key={s.value}
                                        value={String(s.value)}
                                    >
                                        {s.label}
                                    </SelectItem>
                                ))}
                            </SelectContent>
                        </Select>
                        <Select
                            value={
                                filters.partner ? String(filters.partner) : ALL
                            }
                            onValueChange={(v) =>
                                applyFilters({
                                    partner: v === ALL ? undefined : v,
                                })
                            }
                        >
                            <SelectTrigger className="w-56">
                                <SelectValue placeholder="Relationship partner" />
                            </SelectTrigger>
                            <SelectContent>
                                <SelectItem value={ALL}>
                                    All partners
                                </SelectItem>
                                {partners.map((p) => (
                                    <SelectItem
                                        key={p.value}
                                        value={String(p.value)}
                                    >
                                        {p.label}
                                    </SelectItem>
                                ))}
                            </SelectContent>
                        </Select>
                    </CardContent>
                </Card>

                <Card>
                    <CardContent className="p-0">
                        {clients.data.length === 0 ? (
                            <EmptyState
                                icon={Briefcase}
                                title="No clients found"
                                description="Adjust your filters, or onboard the firm's first client."
                                action={
                                    <Button asChild>
                                        <Link href={create()}>
                                            <Plus /> New client
                                        </Link>
                                    </Button>
                                }
                            />
                        ) : (
                            <>
                                <Table>
                                    <TableHeader>
                                        <TableRow>
                                            <TableHead>Client no.</TableHead>
                                            <TableHead>Name</TableHead>
                                            <TableHead>Partner</TableHead>
                                            <TableHead>KYC</TableHead>
                                            <TableHead>Status</TableHead>
                                            <TableHead className="text-right">
                                                Actions
                                            </TableHead>
                                        </TableRow>
                                    </TableHeader>
                                    <TableBody>
                                        {clients.data.map((row) => (
                                            <TableRow key={row.id}>
                                                <TableCell className="font-mono text-xs text-muted-foreground">
                                                    <Link
                                                        href={show(row.id)}
                                                        className="hover:text-primary"
                                                    >
                                                        {row.client_number}
                                                    </Link>
                                                </TableCell>
                                                <TableCell className="font-medium text-foreground">
                                                    <Link
                                                        href={show(row.id)}
                                                        className="hover:text-primary"
                                                    >
                                                        {row.name}
                                                    </Link>
                                                    <span className="ml-2 text-xs text-muted-foreground">
                                                        {row.kind_label}
                                                    </span>
                                                </TableCell>
                                                <TableCell>
                                                    {row.relationship_partner ??
                                                        '—'}
                                                </TableCell>
                                                <TableCell>
                                                    <StatusBadge
                                                        tone={
                                                            row.kyc_completed
                                                                ? 'success'
                                                                : 'warning'
                                                        }
                                                    >
                                                        {row.kyc_completed
                                                            ? 'Complete'
                                                            : 'Pending'}
                                                    </StatusBadge>
                                                </TableCell>
                                                <TableCell>
                                                    <StatusBadge
                                                        tone={
                                                            row.status ===
                                                            'active'
                                                                ? 'success'
                                                                : 'neutral'
                                                        }
                                                    >
                                                        {row.status_label}
                                                    </StatusBadge>
                                                </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 client will be removed. This cannot be undone."
                                                            confirmLabel="Delete client"
                                                            onConfirm={() =>
                                                                router.delete(
                                                                    destroy(
                                                                        row.id,
                                                                    ).url,
                                                                )
                                                            }
                                                            trigger={
                                                                <Button
                                                                    variant="ghost"
                                                                    size="icon-sm"
                                                                >
                                                                    <Trash2 />
                                                                </Button>
                                                            }
                                                        />
                                                    </div>
                                                </TableCell>
                                            </TableRow>
                                        ))}
                                    </TableBody>
                                </Table>
                                <Pagination page={clients} />
                            </>
                        )}
                    </CardContent>
                </Card>
            </div>
        </>
    );
}
