import { Head, Link, router } from '@inertiajs/react';
import { ChevronDown, ShieldCheck } from 'lucide-react';
import DataTable from '@/components/data-table';
import type { DataTableColumn } from '@/components/data-table';
import MemberPage from '@/components/member/member-page';
import StatusBadge from '@/components/member/status-badge';
import { cn } from '@/lib/utils';
import { index } from '@/routes/admin/guarantors';
import { show as loanShow } from '@/routes/admin/loans';
import type { LoanGuarantorItem, Paginated, SelectOption } from '@/types';

type Row = LoanGuarantorItem & {
    activeGuarantees: number;
    loan: { id: number; number: string; statusLabel: string; borrower: string };
};

export default function GuarantorsIndex({
    guarantors,
    limit,
    statusFilter,
    statuses,
}: {
    guarantors: Paginated<Row>;
    limit: number;
    statusFilter: string;
    statuses: SelectOption[];
}) {
    const filterByStatus = (status: string) => {
        const query = new URLSearchParams(window.location.search);

        if (status) {
            query.set('status', status);
        } else {
            query.delete('status');
        }

        query.delete('page');
        router.get(
            `${window.location.pathname}${query.toString() ? `?${query}` : ''}`,
            {},
            { preserveState: true, preserveScroll: true, replace: true },
        );
    };

    const columns: DataTableColumn<Row>[] = [
        {
            key: 'name',
            header: 'Guarantor',
            cell: (row) => (
                <span className="flex min-w-0 items-center gap-3">
                    {row.photoUrl ? (
                        <img
                            src={row.photoUrl}
                            alt=""
                            className="size-9 shrink-0 rounded-full object-cover"
                        />
                    ) : (
                        <span className="size-9 shrink-0 rounded-full bg-surface-100" />
                    )}
                    <span className="min-w-0">
                        <span className="block truncate font-semibold text-ink">
                            {row.name}
                        </span>
                        <span className="block truncate text-xs text-ink-400">
                            {row.phone}
                            {row.memberId && ` · ${row.memberId}`}
                            {row.idNumber && ` · ID ${row.idNumber}`}
                        </span>
                    </span>
                </span>
            ),
        },
        {
            key: 'loan',
            header: 'Guarantees',
            cell: (row) => (
                <Link href={loanShow(row.loan.id)} className="group block">
                    <span className="block font-mono text-xs text-ink-700 group-hover:text-brand">
                        {row.loan.number}
                    </span>
                    <span className="block truncate text-xs text-ink-400">
                        {row.loan.borrower} · {row.loan.statusLabel}
                    </span>
                </Link>
            ),
        },
        {
            key: 'relationship',
            header: 'Relationship',
            hideOnMobile: true,
            className: 'text-xs text-ink-500',
            cell: (row) => `${row.relationship} · ${row.occupation}`,
        },
        {
            key: 'activeGuarantees',
            header: 'Open loans',
            align: 'right',
            cell: (row) => (
                <span
                    className={cn(
                        'font-semibold tabular-nums',
                        row.activeGuarantees >= limit
                            ? 'text-red-600'
                            : 'text-ink-700',
                    )}
                >
                    {row.activeGuarantees} / {limit}
                </span>
            ),
        },
        {
            key: 'status',
            header: 'Status',
            cell: (row) => (
                <span className="flex flex-wrap gap-1">
                    <StatusBadge
                        tone={
                            row.status === 'verified'
                                ? 'success'
                                : row.status === 'rejected'
                                  ? 'failed'
                                  : 'pending'
                        }
                    >
                        {row.statusLabel}
                    </StatusBadge>
                    {!row.hasIdentity && (
                        <StatusBadge tone="neutral">ID incomplete</StatusBadge>
                    )}
                </span>
            ),
        },
    ];

    return (
        <>
            <Head title="Guarantors" />

            <MemberPage
                title="Guarantors"
                description={`Everyone standing behind a loan. One person may guarantee up to ${limit} open loans at a time (change this in System settings).`}
            >
                <DataTable
                    title="All guarantors"
                    description={`${guarantors.total} in total`}
                    columns={columns}
                    page={guarantors}
                    getRowId={(row) => row.id}
                    searchable
                    searchPlaceholder="Search name, phone, ID number or loan number"
                    toolbar={
                        <div className="relative w-full sm:w-auto">
                            <select
                                value={statusFilter}
                                onChange={(event) =>
                                    filterByStatus(event.target.value)
                                }
                                aria-label="Filter by status"
                                className="h-9 w-full appearance-none rounded-md border border-input bg-white pr-8 pl-3 text-sm text-ink shadow-xs outline-none focus-visible:border-brand focus-visible:ring-3 focus-visible:ring-brand/15 sm:w-48"
                            >
                                <option value="">All statuses</option>
                                {statuses.map((status) => (
                                    <option
                                        key={status.value}
                                        value={status.value}
                                    >
                                        {status.label}
                                    </option>
                                ))}
                            </select>
                            <ChevronDown className="pointer-events-none absolute top-1/2 right-2.5 size-4 -translate-y-1/2 text-ink-400" />
                        </div>
                    }
                    empty={{
                        icon: ShieldCheck,
                        title: 'No guarantors yet',
                        description:
                            'Guarantors appear here when members apply for loans.',
                    }}
                />
            </MemberPage>
        </>
    );
}

GuarantorsIndex.layout = {
    breadcrumbs: [{ title: 'Guarantors', href: index() }],
};
