import { Head, Link, router } from '@inertiajs/react';
import { ArrowUpFromLine } from 'lucide-react';
import DataTable from '@/components/data-table';
import type { DataTableColumn } from '@/components/data-table';
import MemberPage from '@/components/member/member-page';
import WithdrawalStatus from '@/components/member/withdrawal-status';
import type { WithdrawalItem } from '@/components/member/withdrawal-status';
import { formatDateTime, formatNaira } from '@/lib/format';
import { cn } from '@/lib/utils';
import { index, show } from '@/routes/admin/withdrawals';
import type { Paginated } from '@/types';

type Row = WithdrawalItem & {
    member: { id: number; name: string; memberId: string };
};

const tabs = [
    ['', 'All'],
    ['pending', 'Pending'],
    ['approved', 'Approved'],
    ['paid', 'Paid'],
    ['rejected', 'Rejected'],
    ['cancelled', 'Cancelled'],
] as const;

export default function AdminWithdrawals({
    withdrawals,
    statusFilter,
    counts,
}: {
    withdrawals: Paginated<Row>;
    statusFilter: string;
    counts: Record<string, number>;
}) {
    const filter = (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}` : ''}`,
            {},
            { preserveScroll: true, replace: true },
        );
    };

    const columns: DataTableColumn<Row>[] = [
        {
            key: 'member',
            header: 'Member',
            cell: (row) => (
                <Link href={show(row.id)} className="group block min-w-0">
                    <span className="block truncate font-semibold text-ink group-hover:text-brand">
                        {row.member.name}
                    </span>
                    <span className="block truncate text-xs text-ink-400">
                        <span className="font-mono">{row.member.memberId}</span>{' '}
                        · {row.reference}
                    </span>
                </Link>
            ),
        },
        {
            key: 'amount',
            header: 'Amount',
            sortable: true,
            align: 'right',
            className: 'font-semibold whitespace-nowrap text-ink tabular-nums',
            cell: (row) => formatNaira(row.amount),
        },
        {
            key: 'paymentMethod',
            header: 'Paid as',
            hideOnMobile: true,
            className: 'text-xs text-ink-500',
            cell: (row) => row.paymentMethodLabel,
        },
        {
            key: 'status',
            header: 'Status',
            cell: (row) => (
                <WithdrawalStatus status={row.status} label={row.statusLabel} />
            ),
        },
        {
            key: 'requestedAt',
            header: 'Requested',
            sortable: true,
            hideOnMobile: true,
            className: 'text-xs whitespace-nowrap text-ink-500',
            cell: (row) => formatDateTime(row.requestedAt),
        },
    ];

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

            <MemberPage
                title="Withdrawals"
                description="Verify each request, approve or reject it, then pay the member and mark it paid."
            >
                <DataTable
                    title="Requests"
                    description={`${withdrawals.total} shown`}
                    columns={columns}
                    page={withdrawals}
                    getRowId={(row) => row.id}
                    searchable
                    searchPlaceholder="Search member, ADS-ID or WD- reference"
                    defaultSort={{ key: 'requestedAt', direction: 'asc' }}
                    toolbar={
                        <div
                            role="tablist"
                            aria-label="Filter by status"
                            className="flex flex-wrap gap-1 rounded-full bg-surface-100 p-1"
                        >
                            {tabs.map(([value, label]) => (
                                <button
                                    key={value || 'all'}
                                    type="button"
                                    role="tab"
                                    aria-selected={statusFilter === value}
                                    onClick={() => filter(value)}
                                    className={cn(
                                        'rounded-full px-2.5 py-1 text-xs font-semibold transition-colors',
                                        statusFilter === value
                                            ? 'bg-white text-ink shadow-landing-sm'
                                            : 'text-ink-500 hover:text-ink',
                                    )}
                                >
                                    {label}{' '}
                                    <span className="text-ink-400">
                                        {counts[value || 'all'] ?? 0}
                                    </span>
                                </button>
                            ))}
                        </div>
                    }
                    empty={{
                        icon: ArrowUpFromLine,
                        title: 'No withdrawals here',
                        description:
                            'Member withdrawal requests will appear here.',
                    }}
                />
            </MemberPage>
        </>
    );
}

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