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 { parseServerDate } from '@/lib/date';
import { cn } from '@/lib/utils';
import { Head, Link, router } from '@inertiajs/react';
import {
    keepPreviousData,
    useQuery,
    useQueryClient,
} from '@tanstack/react-query';
import type { ColumnDef } from '@tanstack/react-table';
import { format } from 'date-fns';
import { Eye, MoreHorizontal, Pencil, Plus, Radio, Trash2 } from 'lucide-react';

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

interface CustomerRow {
    id: string;
    name: string;
    sector: string | null;
    country: string | null;
    location: string | null;
    published_at: string | null;
    status: 'draft' | 'scheduled' | 'published';
    created_at: string;
}

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

// ── Status badge ──────────────────────────────────────────────────────────────

const STATUS_STYLES = {
    draft: 'bg-muted text-muted-foreground',
    scheduled:
        'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400',
    published:
        'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400',
} as const;

function StatusBadge({ status }: { status: CustomerRow['status'] }) {
    return (
        <span
            className={cn(
                'inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-medium capitalize',
                STATUS_STYLES[status],
            )}
        >
            {status}
        </span>
    );
}

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

const FILTER_DEFS = [
    { value: 'all', label: 'All' },
    { value: 'published', label: 'Published' },
    { value: 'scheduled', label: 'Scheduled' },
    { value: 'draft', label: 'Draft' },
];

// ── API fetch ─────────────────────────────────────────────────────────────────

function fetchCustomers(params: TableParams): Promise<CustomersResponse> {
    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/customers?${sp}`);
}

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

function RowActions({
    row,
    onToggle,
}: {
    row: CustomerRow;
    onToggle: () => void;
}) {
    const handleDelete = () => {
        if (!confirm(`Delete customer "${row.name}"?`)) return;
        router.delete(`/admin/customers/${row.id}`, {
            onSuccess: onToggle,
        });
    };

    const handleToggle = () => {
        router.patch(
            `/admin/customers/${row.id}/publish`,
            {},
            { onSuccess: onToggle },
        );
    };

    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</span>
                </button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end" className="w-44">
                <DropdownMenuItem asChild className="gap-2 text-xs">
                    <Link href={`/admin/customers/${row.id}/edit`}>
                        <Pencil className="h-3.5 w-3.5" />
                        Edit
                    </Link>
                </DropdownMenuItem>
                <DropdownMenuItem
                    className="gap-2 text-xs"
                    onClick={handleToggle}
                >
                    {row.status === 'published' ? (
                        <>
                            <Eye className="h-3.5 w-3.5" />
                            Move to draft
                        </>
                    ) : (
                        <>
                            <Radio className="h-3.5 w-3.5 text-emerald-500" />
                            Publish now
                        </>
                    )}
                </DropdownMenuItem>
                <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(
    invalidate: () => void,
): ColumnDef<CustomerRow, unknown>[] {
    return [
        {
            accessorKey: 'name',
            header: 'Name',
            meta: { sortable: true, label: 'Name' },
            cell: ({ row }) => (
                <div className="min-w-0">
                    <Link
                        href={`/admin/customers/${row.original.id}/edit`}
                        className="text-foreground block truncate font-medium hover:opacity-80"
                    >
                        {row.original.name}
                    </Link>
                    <p className="text-muted-foreground mt-0.5 truncate text-[11px]">
                        {row.original.sector ?? '—'}
                    </p>
                </div>
            ),
        },
        {
            accessorKey: 'country',
            header: 'Country',
            meta: { sortable: true, label: 'Country' },
            cell: ({ row }) => (
                <span className="text-muted-foreground text-xs">
                    {[row.original.location, row.original.country]
                        .filter(Boolean)
                        .join(', ') || '—'}
                </span>
            ),
        },
        {
            accessorKey: 'status',
            header: 'Status',
            meta: { sortable: true, label: 'Status' },
            cell: ({ row }) => <StatusBadge status={row.original.status} />,
        },
        {
            accessorKey: 'published_at',
            header: 'Published',
            meta: { sortable: true, label: 'Published' },
            cell: ({ row }) => {
                const d = row.original.published_at;
                return d ? (
                    <span className="text-muted-foreground text-xs tabular-nums">
                        {format(parseServerDate(d), 'dd MMM yyyy')}
                    </span>
                ) : (
                    <span className="text-muted-foreground text-xs">—</span>
                );
            },
        },
        {
            accessorKey: 'created_at',
            header: 'Created',
            meta: { sortable: true, label: 'Created' },
            cell: ({ row }) => (
                <span className="text-muted-foreground text-xs tabular-nums">
                    {format(
                        parseServerDate(row.original.created_at),
                        'dd MMM yyyy',
                    )}
                </span>
            ),
        },
        {
            id: '_actions',
            header: '',
            cell: ({ row }) => (
                <RowActions row={row.original} onToggle={invalidate} />
            ),
            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 CustomersIndex() {
    const { params, setParams } = useDataTable({
        sort: 'created_at',
        dir: 'desc',
    });
    const queryClient = useQueryClient();

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

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

    const { deleteWithUndo } = useDeleteWithUndo();
    const handleBulkDelete = (rows: CustomerRow[]) => {
        const ids = rows.map((r) => r.id);
        deleteWithUndo({
            noun: 'customer',
            count: ids.length,
            onDelete: () => api.post('/admin/customers/bulk-delete', { ids }),
            onUndo: () => api.post('/admin/customers/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="Customers">
            <Head title="Customers" />

            <div className="space-y-6 p-6 lg:p-8">
                <PageHeader
                    title="Customers"
                    description="Institutions showcased on the public customers page"
                    action={
                        <div className="flex items-center gap-2">
                            <Link
                                href="/admin/customers/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/customers/create">
                                    <Plus className="h-4 w-4" />
                                    New customer
                                </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',
                        },
                    ]}
                    searchPlaceholder="Search customers…"
                    noun="customers"
                    getRowId={(row) => String(row.id)}
                />
            </div>
        </AdminLayout>
    );
}
