import AdminLayout from '@/Layouts/AdminLayout';
import { DataTable, type TableMeta } from '@/components/admin/DataTable';
import PageHeader from '@/components/admin/PageHeader';
import { ConfirmDialog } from '@/components/ui/confirm-dialog';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuSeparator,
    DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { useDataTable, type TableParams } from '@/hooks/useDataTable';
import { api } from '@/lib/api';
import { parseServerDate } from '@/lib/date';
import { cn } from '@/lib/utils';
import { Head, Link } from '@inertiajs/react';
import {
    keepPreviousData,
    useQuery,
    useQueryClient,
} from '@tanstack/react-query';
import type { ColumnDef } from '@tanstack/react-table';
import { formatDistanceToNow } from 'date-fns';
import {
    ArchiveRestore,
    ArrowLeft,
    MoreHorizontal,
    ShieldOff,
    Trash2,
} from 'lucide-react';
import { useState } from 'react';
import { toast } from 'sonner';

// ── Types ─────────────────────────────────────────────────────────────────────

interface TrashedCurrency {
    id: string;
    code: string;
    name: string;
    symbol: string;
    rate: number;
    decimals: number;
    is_base: boolean;
    is_enabled: boolean;
    deleted_at: string;
}

interface TrashResponse {
    data: TrashedCurrency[];
    meta: TableMeta;
    filter_counts: Record<string, number>;
}

// ── API helpers ───────────────────────────────────────────────────────────────

function fetchTrash(params: TableParams): Promise<TrashResponse> {
    const sp = new URLSearchParams({ page: String(params.page) });
    if (params.sort) sp.set('sort', params.sort);
    if (params.dir !== 'asc') sp.set('dir', params.dir);
    if (params.search) sp.set('search', params.search);
    return api.get(`/admin/api/currencies/trash?${sp}`);
}

const apiRestore = (id: string) => api.post(`/admin/currencies/${id}/restore`);
const apiForceDelete = (id: string) =>
    api.delete(`/admin/currencies/${id}/force`);
const apiBulkRestore = (ids: string[]) =>
    api.post('/admin/currencies/bulk-restore', { ids });
const apiBulkForceDelete = (ids: string[]) =>
    api.post('/admin/currencies/bulk-force-delete', { ids });

// ── Delete dialog descriptions ────────────────────────────────────────────────

function SingleDeleteDescription({ currency }: { currency: TrashedCurrency }) {
    return (
        <p>
            You are about to permanently delete the currency{' '}
            <code className="bg-muted text-foreground rounded px-1.5 py-0.5 font-mono text-xs">
                {currency.code}
            </code>{' '}
            ({currency.name}). This action <strong>cannot be undone</strong>.
        </p>
    );
}

function BulkDeleteDescription({
    currencies,
}: {
    currencies: TrashedCurrency[];
}) {
    return (
        <p>
            You are about to permanently delete{' '}
            <strong>{currencies.length} currencies</strong> (
            {currencies.map((c) => c.code).join(', ')}). This action{' '}
            <strong>cannot be undone</strong>.
        </p>
    );
}

// ── Row actions ───────────────────────────────────────────────────────────────

function RowActions({
    currency,
    onRestore,
    onForceDelete,
}: {
    currency: TrashedCurrency;
    onRestore: (c: TrashedCurrency) => void;
    onForceDelete: (c: TrashedCurrency) => void;
}) {
    return (
        <DropdownMenu>
            <DropdownMenuTrigger asChild>
                <button className="text-muted-foreground hover:bg-muted/60 hover:text-foreground flex h-7 w-7 items-center justify-center rounded-md transition-colors focus:outline-none">
                    <MoreHorizontal className="h-4 w-4" />
                    <span className="sr-only">Actions for {currency.code}</span>
                </button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end" className="w-48">
                <DropdownMenuItem
                    className="gap-2 text-xs"
                    onClick={() => onRestore(currency)}
                >
                    <ArchiveRestore className="h-3.5 w-3.5" />
                    Restore
                </DropdownMenuItem>
                <DropdownMenuSeparator />
                <DropdownMenuItem
                    className="gap-2 text-xs text-red-600 focus:text-red-600 dark:text-red-400 dark:focus:text-red-400"
                    onClick={() => onForceDelete(currency)}
                >
                    <ShieldOff className="h-3.5 w-3.5" />
                    Delete permanently
                </DropdownMenuItem>
            </DropdownMenuContent>
        </DropdownMenu>
    );
}

// ── Empty meta ────────────────────────────────────────────────────────────────

const EMPTY_META: TableMeta = {
    current_page: 1,
    last_page: 1,
    total: 0,
    per_page: 25,
    from: 0,
    to: 0,
};

// ── Page ──────────────────────────────────────────────────────────────────────

type DeleteTarget =
    | { kind: 'single'; currency: TrashedCurrency }
    | { kind: 'bulk'; currencies: TrashedCurrency[] };

export default function CurrenciesTrash() {
    const qc = useQueryClient();
    const { params, setParams } = useDataTable({
        sort: 'deleted_at',
        dir: 'desc',
    });

    const { data, isLoading, isFetching } = useQuery({
        queryKey: ['admin.currencies.trash', params],
        queryFn: () => fetchTrash(params),
        placeholderData: keepPreviousData,
    });

    const invalidate = () => {
        qc.invalidateQueries({ queryKey: ['admin.currencies.trash'] });
        qc.invalidateQueries({ queryKey: ['admin.currencies'] });
    };

    // ── Delete modal state ─────────────────────────────────────────────────────
    const [deleteTarget, setDeleteTarget] = useState<DeleteTarget | null>(null);
    const [deleting, setDeleting] = useState(false);

    const openSingleDelete = (currency: TrashedCurrency) =>
        setDeleteTarget({ kind: 'single', currency });
    const openBulkDelete = (currencies: TrashedCurrency[]) =>
        setDeleteTarget({ kind: 'bulk', currencies });
    const closeDelete = () => {
        if (!deleting) setDeleteTarget(null);
    };

    const handleConfirmDelete = async () => {
        if (!deleteTarget) return;
        setDeleting(true);
        try {
            if (deleteTarget.kind === 'single') {
                await apiForceDelete(deleteTarget.currency.id);
                toast.success(
                    `${deleteTarget.currency.code} permanently deleted`,
                );
            } else {
                await apiBulkForceDelete(
                    deleteTarget.currencies.map((c) => c.id),
                );
                toast.success(
                    `${deleteTarget.currencies.length} currencies permanently deleted`,
                );
            }
            invalidate();
            setDeleteTarget(null);
        } catch {
            toast.error('Failed to permanently delete');
        } finally {
            setDeleting(false);
        }
    };

    // ── Restore handlers ───────────────────────────────────────────────────────
    const handleRestore = async (currency: TrashedCurrency) => {
        try {
            await apiRestore(currency.id);
            toast.success(`${currency.code} restored`);
            invalidate();
        } catch {
            toast.error('Failed to restore currency');
        }
    };

    const handleBulkRestore = async (rows: TrashedCurrency[]) => {
        try {
            await apiBulkRestore(rows.map((c) => c.id));
            toast.success(`${rows.length} currencies restored`);
            invalidate();
        } catch {
            toast.error('Failed to restore currencies');
        }
    };

    // ── Columns ────────────────────────────────────────────────────────────────
    const columns: ColumnDef<TrashedCurrency, unknown>[] = [
        {
            accessorKey: 'code',
            header: 'Code',
            meta: { sortable: true, label: 'Code' },
            cell: ({ row }) => (
                <span className="text-foreground/60 font-mono text-sm font-medium line-through">
                    {row.original.code}
                </span>
            ),
        },
        {
            accessorKey: 'name',
            header: 'Name',
            meta: { sortable: true, label: 'Name' },
            cell: ({ row }) => (
                <span className="text-muted-foreground text-sm">
                    {row.original.name}
                </span>
            ),
        },
        {
            accessorKey: 'rate',
            header: 'Rate',
            meta: { sortable: true, label: 'Rate' },
            cell: ({ row }) => (
                <span className="text-muted-foreground text-sm tabular-nums">
                    {row.original.rate.toLocaleString('en-US', {
                        maximumFractionDigits: 8,
                    })}
                </span>
            ),
        },
        {
            accessorKey: 'deleted_at',
            header: 'Deleted',
            meta: { sortable: true, label: 'Deleted' },
            cell: ({ row }) => (
                <span className="text-muted-foreground text-xs">
                    {formatDistanceToNow(
                        parseServerDate(row.original.deleted_at),
                        { addSuffix: true },
                    )}
                </span>
            ),
        },
        {
            id: '_actions',
            header: '',
            cell: ({ row }) => (
                <RowActions
                    currency={row.original}
                    onRestore={handleRestore}
                    onForceDelete={openSingleDelete}
                />
            ),
            enableHiding: false,
        },
    ];

    return (
        <AdminLayout
            title="Currencies — Trash"
            breadcrumbs={[
                { label: 'Billing' },
                { label: 'Currencies', href: '/admin/currencies' },
                { label: 'Trash' },
            ]}
        >
            <Head title="Currencies — Trash" />

            <div className="space-y-6 p-6 lg:p-8">
                <PageHeader
                    title="Currencies Trash"
                    description="Deleted currencies are kept here. Restore or permanently delete them."
                    action={
                        <Link
                            href="/admin/currencies"
                            className={cn(
                                'border-border flex items-center gap-1.5 rounded-lg border px-3 py-2',
                                'text-muted-foreground hover:bg-muted/40 hover:text-foreground text-xs font-medium transition-colors',
                            )}
                        >
                            <ArrowLeft className="h-3.5 w-3.5" />
                            Back to Currencies
                        </Link>
                    }
                />

                <DataTable
                    columns={columns}
                    data={data?.data ?? []}
                    meta={data?.meta ?? EMPTY_META}
                    params={params}
                    isLoading={isLoading}
                    isFetching={isFetching}
                    onParamsChange={setParams}
                    quickFilters={[
                        {
                            label: 'All Trash',
                            value: 'all',
                            count: data?.filter_counts.all,
                        },
                    ]}
                    bulkActions={[
                        {
                            label: 'Restore',
                            icon: ArchiveRestore,
                            onClick: handleBulkRestore,
                        },
                        {
                            label: 'Delete permanently',
                            icon: Trash2,
                            onClick: openBulkDelete,
                            variant: 'destructive',
                        },
                    ]}
                    onRefresh={invalidate}
                    searchPlaceholder="Search deleted currencies…"
                    noun="currencies"
                    getRowId={(row) => String(row.id)}
                />
            </div>

            {/* ── Permanent delete confirmation modal ─────────────────────── */}
            <ConfirmDialog
                open={deleteTarget !== null}
                onOpenChange={closeDelete}
                title="Permanently delete currency?"
                description={
                    deleteTarget?.kind === 'single' ? (
                        <SingleDeleteDescription
                            currency={deleteTarget.currency}
                        />
                    ) : deleteTarget?.kind === 'bulk' ? (
                        <BulkDeleteDescription
                            currencies={deleteTarget.currencies}
                        />
                    ) : null
                }
                confirmLabel="Delete permanently"
                loading={deleting}
                onConfirm={handleConfirmDelete}
            />
        </AdminLayout>
    );
}
