import { Form, Head, Link } from '@inertiajs/react';
import { Check, Eye, FileCheck2, FileText, X } from 'lucide-react';
import { useState } from 'react';
import KycReviewController from '@/actions/App/Http/Controllers/Admin/KycReviewController';
import DataTable from '@/components/data-table';
import type { DataTableColumn } from '@/components/data-table';
import InputError from '@/components/input-error';
import MemberPage from '@/components/member/member-page';
import StatusBadge from '@/components/member/status-badge';
import type { BadgeTone } from '@/components/member/status-badge';
import { Button } from '@/components/ui/button';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { formatDateTime } from '@/lib/format';
import { index, show } from '@/routes/admin/kyc';
import type { Paginated } from '@/types';

type QueueItem = {
    id: number;
    typeLabel: string;
    originalName: string;
    uploadedAt: string | null;
    mimeType: string;
    member: { name: string; email: string; kycStatus: string };
};

const statusTones: Record<string, BadgeTone> = {
    Verified: 'success',
    Pending: 'pending',
    Rejected: 'failed',
};

export default function KycQueue({
    documents,
}: {
    documents: Paginated<QueueItem>;
}) {
    const [rejecting, setRejecting] = useState<QueueItem | null>(null);

    const columns: DataTableColumn<QueueItem>[] = [
        {
            key: 'member',
            header: 'Member',
            sortable: true,
            cell: (document) => (
                <span className="block min-w-0">
                    <span className="block truncate font-semibold text-ink">
                        {document.member.name}
                    </span>
                    <span className="block truncate text-xs text-ink-400">
                        {document.member.email}
                    </span>
                </span>
            ),
        },
        {
            key: 'type',
            header: 'Document',
            sortable: true,
            cell: (document) => (
                <span className="flex min-w-0 items-center gap-2">
                    <FileText className="size-4 shrink-0 text-ink-400" />
                    <span className="min-w-0">
                        <span className="block truncate text-ink">
                            {document.typeLabel}
                        </span>
                        <span className="block max-w-48 truncate text-xs text-ink-400">
                            {document.originalName}
                        </span>
                    </span>
                </span>
            ),
        },
        {
            key: 'uploadedAt',
            header: 'Uploaded',
            sortable: true,
            hideOnMobile: true,
            className: 'whitespace-nowrap text-xs text-ink-500',
            cell: (document) => formatDateTime(document.uploadedAt),
        },
        {
            key: 'status',
            header: 'Member status',
            hideOnMobile: true,
            cell: (document) => (
                <StatusBadge
                    tone={statusTones[document.member.kycStatus] ?? 'neutral'}
                >
                    {document.member.kycStatus}
                </StatusBadge>
            ),
        },
        {
            key: 'actions',
            header: <span className="sr-only">Actions</span>,
            align: 'right',
            className: 'w-px whitespace-nowrap',
            cell: (document) => (
                <span className="inline-flex items-center gap-1.5">
                    <Link
                        href={show(document.id)}
                        className="inline-flex h-8 items-center gap-1 rounded-md border border-input px-2.5 text-sm font-medium text-ink-700 hover:bg-surface-50"
                    >
                        <Eye className="size-3.5" />
                        View
                    </Link>
                    <Form
                        {...KycReviewController.approve.form(document.id)}
                        options={{ preserveScroll: true }}
                    >
                        {({ processing }) => (
                            <Button
                                size="sm"
                                disabled={processing}
                                aria-label={`Approve ${document.typeLabel} for ${document.member.name}`}
                            >
                                <Check className="size-3.5" />
                                Approve
                            </Button>
                        )}
                    </Form>
                    <Button
                        type="button"
                        variant="outline"
                        size="sm"
                        onClick={() => setRejecting(document)}
                        aria-label={`Reject ${document.typeLabel} for ${document.member.name}`}
                    >
                        <X className="size-3.5" />
                        Reject
                    </Button>
                </span>
            ),
        },
    ];

    return (
        <>
            <Head title="KYC review" />

            <MemberPage
                title="KYC review"
                description="Open each document to check it before deciding. Oldest uploads are listed first."
            >
                <DataTable
                    title="Waiting for review"
                    description={`${documents.total} ${documents.total === 1 ? 'document' : 'documents'}`}
                    columns={columns}
                    page={documents}
                    getRowId={(document) => document.id}
                    searchable
                    searchPlaceholder="Search member, email or file"
                    defaultSort={{ key: 'uploadedAt', direction: 'asc' }}
                    empty={{
                        icon: FileCheck2,
                        title: 'Nothing to review',
                        description:
                            'New uploads from members will appear here.',
                    }}
                />
            </MemberPage>

            <Dialog
                open={rejecting !== null}
                onOpenChange={(isOpen) => !isOpen && setRejecting(null)}
            >
                <DialogContent className="sm:max-w-md">
                    {rejecting && (
                        <>
                            <DialogHeader>
                                <DialogTitle>Reject document</DialogTitle>
                                <DialogDescription>
                                    {rejecting.typeLabel} from{' '}
                                    {rejecting.member.name}. The member will see
                                    your reason and can upload a new copy.
                                </DialogDescription>
                            </DialogHeader>
                            <Form
                                {...KycReviewController.reject.form(
                                    rejecting.id,
                                )}
                                options={{ preserveScroll: true }}
                                onSuccess={() => setRejecting(null)}
                                className="grid gap-3"
                            >
                                {({ processing, errors }) => (
                                    <>
                                        <div className="grid gap-2">
                                            <Label htmlFor="reason" required>
                                                Reason the member will see
                                            </Label>
                                            <textarea
                                                id="reason"
                                                name="reason"
                                                required
                                                minLength={5}
                                                maxLength={500}
                                                rows={3}
                                                autoFocus
                                                className="rounded-md border border-input bg-white px-3 py-2 text-sm outline-none focus-visible:border-brand focus-visible:ring-3 focus-visible:ring-brand/15"
                                                placeholder="e.g. The photo is blurry — please upload a clearer copy."
                                            />
                                            <InputError
                                                message={errors.reason}
                                            />
                                        </div>
                                        <div className="flex justify-end gap-2">
                                            <Button
                                                type="button"
                                                variant="ghost"
                                                onClick={() =>
                                                    setRejecting(null)
                                                }
                                            >
                                                Cancel
                                            </Button>
                                            <Button
                                                variant="destructive"
                                                disabled={processing}
                                            >
                                                Reject document
                                            </Button>
                                        </div>
                                    </>
                                )}
                            </Form>
                        </>
                    )}
                </DialogContent>
            </Dialog>
        </>
    );
}

KycQueue.layout = {
    breadcrumbs: [{ title: 'KYC review', href: index() }],
};
