import { ImportItem } from '@/components/ImportList';
import { Button } from '@/components/ui/button';
import { router } from '@inertiajs/react';
import { type ColumnDef } from '@tanstack/react-table';
import { Download, RefreshCw } from 'lucide-react';
import { toast } from 'sonner';

export const importTableColumns = (): ColumnDef<ImportItem>[] => [
    {
        accessorKey: 'id',
        header: 'ID',
        enableSorting: true,
        cell: ({ row }) => <span className="font-medium">#{row.original.id}</span>,
    },
    {
        accessorKey: 'model_type',
        header: 'Model',
        enableSorting: true,
        cell: ({ row }) => row.original.model_type,
    },
    {
        accessorKey: 'creator_name',
        header: 'Created By',
        enableSorting: false,
        cell: ({ row }) => {
            const name = row.original.creator_name || `User #${row.original.created_by ?? '-'}`;
            const email = row.original.creator_email;
            const initials = name
                .split(/\s+/)
                .slice(0, 2)
                .map((p) => p.charAt(0))
                .join('')
                .toUpperCase();
            return (
                <div className="flex items-center gap-2">
                    <div className="flex h-8 w-8 items-center justify-center rounded-full bg-gradient-to-br from-brand-500 to-brand-600 text-[11px] font-semibold text-white shadow">
                        {initials}
                    </div>
                    <div className="flex flex-col leading-tight">
                        <span className="text-xs font-medium text-gray-900">{name}</span>
                        {email && <span className="text-[10px] text-gray-500">{email}</span>}
                    </div>
                </div>
            );
        },
    },
    {
        accessorKey: 'status',
        header: 'Status',
        enableSorting: true,
        cell: ({ row }) => {
            const raw = row.original.status as any;
            const label =
                typeof raw === 'number'
                    ? ({ 2: 'Pending', 10: 'Processing', 5: 'Completed', 7: 'Failed' } as Record<number, string>)[raw] || 'Unknown'
                    : (row.original as any).status_label || String(raw);
            const lower = label.toLowerCase();
            const color =
                lower === 'failed'
                    ? 'bg-red-100 text-red-700'
                    : lower === 'processing'
                      ? 'bg-yellow-100 text-yellow-700'
                      : lower === 'pending'
                        ? 'bg-gray-100 text-gray-700'
                        : 'bg-green-100 text-green-700';
            return <span className={`rounded px-2 py-1 text-xs font-semibold ${color}`}>{label}</span>;
        },
    },
    {
        accessorKey: 'progress',
        header: 'Progress',
        enableSorting: true,
        cell: ({ row }) => {
            const { progress, total_records, success_count, failure_count } = row.original;
            const pct = progress ?? 0;
            return (
                <div className="space-y-1">
                    <div className="h-2 w-32 overflow-hidden rounded bg-gray-200">
                        <div className="h-full bg-brand-500" style={{ width: `${pct}%` }} />
                    </div>
                    <div className="flex flex-wrap items-center gap-1 text-[10px] font-medium">
                        <span className="rounded bg-gray-800 px-1.5 py-0.5 text-[9px] font-semibold text-white tracking-wide">{pct}%</span>
                        <span className="text-gray-500">•</span>
                        <span className="rounded bg-green-100 px-1.5 py-0.5 text-[9px] font-semibold text-green-700">
                            {(success_count ?? 0)} ok
                        </span>
                        <span className="text-gray-400">/</span>
                        <span className={`rounded px-1.5 py-0.5 text-[9px] font-semibold ${ (failure_count ?? 0) > 0 ? 'bg-red-100 text-red-700' : 'bg-gray-100 text-gray-500' }`}>
                            {(failure_count ?? 0)} err
                        </span>
                        {typeof total_records === 'number' && (
                            <span className="ml-1 text-[9px] text-gray-400">of {total_records}</span>
                        )}
                    </div>
                </div>
            );
        },
    },
    {
        accessorKey: 'started_at',
        header: 'Started',
        enableSorting: true,
        cell: ({ row }) => row.original.started_at || '-',
    },
    {
        accessorKey: 'completed_at',
        header: 'Completed',
        enableSorting: true,
        cell: ({ row }) => row.original.completed_at || '-',
    },
    {
        id: 'actions',
        header: 'Actions',
        enableSorting: false,
        enableHiding: false,
        cell: ({ row }) => {
            const imp = row.original;
            const hasFailures = Number(imp.failure_count) > 0;
            // detect skipped-only imports via _meta in error_log
            const hasSkippedMeta = Array.isArray(imp.error_log)
                ? imp.error_log.some((e: any) => e && typeof e === 'object' && e._meta && e._meta.skipped_count > 0)
                : false;
            return (
                <div className="flex items-center gap-2">
                    {hasFailures && (
                        <Button
                            size="sm"
                            variant="outline"
                            onClick={() => {
                                router.post(
                                    route('imports.retry', imp.id),
                                    {},
                                    {
                                        onSuccess: () => toast.success(`Retry started for #${imp.id}`),
                                    },
                                );
                            }}
                        >
                            <RefreshCw className="mr-1 size-3" /> Retry
                        </Button>
                    )}
                    {(hasFailures || hasSkippedMeta) && (
                        <Button
                            size="sm"
                            variant="outline"
                            onClick={() => {
                                window.open(route('imports.export-errors', imp.id), '_blank');
                            }}
                        >
                            <Download className="mr-1 size-3" /> Errors
                        </Button>
                    )}
                </div>
            );
        },
    },
];
