import AdminLayout from '@/Layouts/AdminLayout';
import { DataTable, type TableMeta } from '@/components/admin/DataTable';
import PageHeader from '@/components/admin/PageHeader';
import { Button } from '@/components/ui/button';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuSeparator,
    DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { useDataTable, type TableParams } from '@/hooks/useDataTable';
import { useDeleteWithUndo } from '@/hooks/useDeleteWithUndo';
import { api } from '@/lib/api';
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 {
    Eye,
    EyeOff,
    MoreHorizontal,
    Pencil,
    Plus,
    Trash2,
} from 'lucide-react';
import { toast } from 'sonner';

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

interface CurrencyRow {
    id: string;
    code: string;
    name: string;
    symbol: string;
    rate: number;
    decimals: number;
    is_base: boolean;
    is_enabled: boolean;
    sort_order: number;
    created_at: string | null;
}

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

// ── Quick filters ─────────────────────────────────────────────────────────────

const FILTER_DEFS = [
    { value: 'all', label: 'All' },
    { value: 'enabled', label: 'Enabled' },
    { value: 'disabled', label: 'Disabled' },
];

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

function fetchCurrencies(params: TableParams): Promise<CurrenciesResponse> {
    const sp = new URLSearchParams({ page: String(params.page) });
    if (params.filter && params.filter !== 'all')
        sp.set('filter', params.filter);
    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?${sp}`);
}

// ── Helpers ───────────────────────────────────────────────────────────────────

function formatRate(rate: number): string {
    return rate.toLocaleString('en-US', {
        minimumFractionDigits: 0,
        maximumFractionDigits: 8,
    });
}

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

function RowActions({
    row,
    onChanged,
}: {
    row: CurrencyRow;
    onChanged: () => void;
}) {
    const handleToggle = async () => {
        try {
            await api.patch(`/admin/currencies/${row.id}/toggle-enabled`);
            toast.success(
                row.is_enabled ? `${row.code} disabled` : `${row.code} enabled`,
            );
            onChanged();
        } catch (err) {
            toast.error(
                (err as Error).message ?? 'Failed to update currency status',
            );
        }
    };

    const handleDelete = async () => {
        if (!confirm(`Move ${row.code} to trash?`)) return;
        try {
            await api.delete(`/admin/currencies/${row.id}`);
            toast.success(`${row.code} moved to trash`);
            onChanged();
        } catch (err) {
            toast.error((err as Error).message ?? 'Failed to delete currency');
        }
    };

    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 {row.code}</span>
                </button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end" className="w-44">
                <DropdownMenuItem asChild className="gap-2 text-xs">
                    <Link href={`/admin/currencies/${row.id}/edit`}>
                        <Pencil className="h-3.5 w-3.5" />
                        Edit
                    </Link>
                </DropdownMenuItem>
                {!row.is_base && (
                    <DropdownMenuItem
                        className="gap-2 text-xs"
                        onClick={handleToggle}
                    >
                        {row.is_enabled ? (
                            <>
                                <EyeOff className="h-3.5 w-3.5" />
                                Disable
                            </>
                        ) : (
                            <>
                                <Eye className="h-3.5 w-3.5" />
                                Enable
                            </>
                        )}
                    </DropdownMenuItem>
                )}
                {!row.is_base && (
                    <>
                        <DropdownMenuSeparator />
                        <DropdownMenuItem
                            className="text-destructive focus:text-destructive gap-2 text-xs"
                            onClick={handleDelete}
                        >
                            <Trash2 className="h-3.5 w-3.5" />
                            Delete
                        </DropdownMenuItem>
                    </>
                )}
            </DropdownMenuContent>
        </DropdownMenu>
    );
}

// ── Column definitions ────────────────────────────────────────────────────────

function buildColumns(
    onChanged: () => void,
): ColumnDef<CurrencyRow, unknown>[] {
    return [
        {
            accessorKey: 'code',
            header: 'Code',
            meta: { sortable: true, label: 'Code' },
            cell: ({ row }) => (
                <div className="flex items-center gap-2">
                    <Link
                        href={`/admin/currencies/${row.original.id}/edit`}
                        className="text-foreground font-semibold tabular-nums hover:opacity-80"
                    >
                        {row.original.code}
                    </Link>
                    {row.original.is_base && (
                        <span className="bg-primary/10 text-primary rounded-full px-2 py-0.5 text-[10px] font-bold">
                            Base
                        </span>
                    )}
                </div>
            ),
        },
        {
            accessorKey: 'name',
            header: 'Name',
            meta: { sortable: true, label: 'Name' },
            cell: ({ row }) => (
                <span className="text-muted-foreground text-sm">
                    {row.original.name}
                </span>
            ),
        },
        {
            accessorKey: 'symbol',
            header: 'Symbol',
            meta: { label: 'Symbol' },
            cell: ({ row }) => (
                <span className="text-foreground text-sm">
                    {row.original.symbol}
                </span>
            ),
        },
        {
            accessorKey: 'rate',
            header: 'Rate per base unit',
            meta: { sortable: true, label: 'Rate' },
            cell: ({ row }) => (
                <span className="text-foreground text-sm tabular-nums">
                    {formatRate(row.original.rate)}
                </span>
            ),
        },
        {
            accessorKey: 'decimals',
            header: 'Decimals',
            meta: { sortable: true, label: 'Decimals' },
            cell: ({ row }) => (
                <span className="text-muted-foreground text-sm tabular-nums">
                    {row.original.decimals}
                </span>
            ),
        },
        {
            accessorKey: 'is_enabled',
            header: 'Status',
            meta: { label: 'Status' },
            cell: ({ row }) => (
                <span
                    className={cn(
                        'inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-medium',
                        row.original.is_enabled
                            ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400'
                            : 'bg-muted text-muted-foreground',
                    )}
                >
                    {row.original.is_enabled ? 'Enabled' : 'Disabled'}
                </span>
            ),
        },
        {
            id: '_actions',
            header: '',
            cell: ({ row }) => (
                <RowActions row={row.original} onChanged={onChanged} />
            ),
            enableHiding: false,
        },
    ];
}

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

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

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

export default function CurrenciesIndex() {
    const { params, setParams } = useDataTable({
        sort: 'sort_order',
        dir: 'asc',
    });
    const queryClient = useQueryClient();

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

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

    const { deleteWithUndo } = useDeleteWithUndo();
    const handleBulkDelete = (rows: CurrencyRow[]) => {
        const deletable = rows.filter((r) => !r.is_base);
        if (!deletable.length) {
            toast.error(
                'No deletable currencies selected (the base currency is protected)',
            );
            return;
        }
        const ids = deletable.map((r) => r.id);
        deleteWithUndo({
            noun: 'currency',
            pluralNoun: 'currencies',
            count: ids.length,
            onDelete: () => api.post('/admin/currencies/bulk-delete', { ids }),
            onUndo: () => api.post('/admin/currencies/bulk-restore', { ids }),
            onSuccess: invalidate,
        });
    };

    const filterCounts = data?.filter_counts ?? {};
    const quickFilters = FILTER_DEFS.map((f) => ({
        ...f,
        count: filterCounts[f.value] ?? 0,
    }));

    const columns = buildColumns(invalidate);

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

            <div className="space-y-6 p-6 lg:p-8">
                <PageHeader
                    title="Currencies"
                    description="Display currencies and their conversion rates relative to the base currency. Prices convert using these rates when a visitor selects a currency."
                    action={
                        <div className="flex items-center gap-2">
                            <Link
                                href="/admin/currencies/trash"
                                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',
                                )}
                            >
                                <Trash2 className="h-3.5 w-3.5" />
                                Trash
                            </Link>
                            <Button asChild size="sm" className="gap-2">
                                <Link href="/admin/currencies/create">
                                    <Plus className="h-4 w-4" />
                                    New Currency
                                </Link>
                            </Button>
                        </div>
                    }
                />

                <DataTable
                    columns={columns}
                    data={data?.data ?? []}
                    meta={data?.meta ?? EMPTY_META}
                    params={params}
                    isLoading={isLoading}
                    isFetching={isFetching}
                    onParamsChange={setParams}
                    quickFilters={quickFilters}
                    bulkActions={[
                        {
                            label: 'Delete',
                            icon: Trash2,
                            onClick: handleBulkDelete,
                            variant: 'destructive',
                        },
                    ]}
                    onRefresh={invalidate}
                    searchPlaceholder="Search currencies…"
                    noun="currencies"
                    getRowId={(row) => String(row.id)}
                />
            </div>
        </AdminLayout>
    );
}
