import type { ColumnDef } from '@tanstack/table-core';
import type { Doda } from '$lib/api/dashboard/a76/general_catalogs/doda';
import { renderComponent, renderSnippet } from '$lib/components/ui/data-table';
import { createRawSnippet } from 'svelte';
import DataTableActions from './data-table-actions.svelte';
import { getLocale } from '$lib/paraglide/runtime';
import { dodaFormT, type DodaFormKey } from '$lib/i18n/doda-form-strings';

/**
 * doda_date se almacena como Integer con formato YYYYMMDD (ej. 20180409).
 * Lo convertimos a DD/MM/YYYY para mostrar.
 */
function formatDodaDate(val?: number | string | null): string {
    if (!val) return '-';
    const s = String(val);
    if (s.length === 8) {
        const y = s.slice(0, 4);
        const m = s.slice(4, 6);
        const d = s.slice(6, 8);
        return `${d}/${m}/${y}`;
    }
    // Fallback: ISO string
    try {
        return new Date(s).toLocaleDateString(getLocale() === 'en' ? 'en-US' : 'es-MX', {
            day: '2-digit',
            month: '2-digit',
            year: 'numeric'
        });
    } catch {
        return s;
    }
}

const STATUS_CLASSES: Record<string, string> = {
    GENERADO:   'bg-blue-100   text-blue-800   dark:bg-blue-900/30   dark:text-blue-300',
    'EN PROCESO':'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-300',
    VALIDADO:   'bg-green-100  text-green-800  dark:bg-green-900/30  dark:text-green-300',
    PENDIENTE:  'bg-gray-100   text-gray-700   dark:bg-gray-800/50   dark:text-gray-300',
    ELIMINADO:  'bg-red-100    text-red-700    dark:bg-red-900/30    dark:text-red-300',
};

export function createColumns(
    loc: 'en' | 'es',
    onSuccess?: () => void,
    {
        canEdit = true,
        canDelete = true,
        dodaListBasePath = '/dashboard/despacho/doda'
    }: { canEdit?: boolean; canDelete?: boolean; dodaListBasePath?: string } = {}
): ColumnDef<Doda>[] {
    const t = (k: DodaFormKey) => dodaFormT(loc, k);
    return [
        {
            accessorKey: 'id',
            header: t('list_col_folio'),
            size: 70,
            cell: ({ row }) => {
                const n = row.original.id;
                const s = createRawSnippet(() => ({
                    render: () =>
                        `<code class="rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm font-semibold">${n}</code>`
                }));
                return renderSnippet(s, {});
            }
        },
        {
            accessorKey: 'doda_date',
            header: t('list_col_doda_date'),
            size: 100,
            cell: ({ row }) => {
                const d = formatDodaDate(row.original.doda_date);
                const s = createRawSnippet(() => ({
                    render: () => `<span class="text-sm tabular-nums">${d}</span>`
                }));
                return renderSnippet(s, {});
            }
        },
        {
            accessorKey: 'dispatch_customs',
            header: t('list_col_desp'),
            size: 60,
            cell: ({ row }) => row.original.dispatch_customs || '-'
        },
        {
            accessorKey: 'patent',
            header: t('list_col_patent'),
            size: 70,
            cell: ({ row }) => row.original.patent || '-'
        },
        {
            accessorKey: 'pedimentos',
            header: t('list_col_pedimentos'),
            cell: ({ row }) => {
                const v = row.original.pedimentos || '-';
                const s = createRawSnippet(() => ({
                    render: () =>
                        `<span class="block truncate max-w-[160px]" title="${v}">${v}</span>`
                }));
                return renderSnippet(s, {});
            }
        },
        {
            accessorKey: 'shipments',
            header: t('list_col_remesas'),
            size: 90,
            cell: ({ row }) => row.original.shipments || '-'
        },
        {
            accessorKey: 'integration_number',
            header: t('list_col_integracion'),
            size: 110,
            cell: ({ row }) => {
                const v = row.original.integration_number;
                const s = createRawSnippet(() => ({
                    render: () =>
                        v
                            ? `<code class="rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm font-semibold">${v}</code>`
                            : `<span class="text-muted-foreground">-</span>`
                }));
                return renderSnippet(s, {});
            }
        },
        {
            accessorKey: 'transaction_number',
            header: t('list_col_trans'),
            cell: ({ row }) => {
                const v = row.original.transaction_number || '-';
                const s = createRawSnippet(() => ({
                    render: () =>
                        `<span class="font-mono text-xs block truncate max-w-[160px]" title="${v}">${v}</span>`
                }));
                return renderSnippet(s, {});
            }
        },
        {
            accessorKey: 'transport_identification',
            header: t('list_col_id_transport'),
            size: 120,
            cell: ({ row }) => row.original.transport_identification || '-'
        },
        {
            accessorKey: 'caat',
            header: t('list_col_caat'),
            size: 70,
            cell: ({ row }) => row.original.caat || '-'
        },
        {
            accessorKey: 'last_user',
            header: t('list_col_user'),
            size: 90,
            cell: ({ row }) => row.original.last_user || '-'
        },
        {
            accessorKey: 'status',
            header: t('list_col_status'),
            size: 110,
            cell: ({ row }) => {
                const status = (row.original.status || '').toUpperCase();
                const cls = STATUS_CLASSES[status] ?? 'bg-gray-100 text-gray-700 dark:bg-gray-800/50 dark:text-gray-300';
                const s = createRawSnippet(() => ({
                    render: () =>
                        `<span class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium whitespace-nowrap ${cls}">${status || '-'}</span>`
                }));
                return renderSnippet(s, {});
            }
        },
        {
            id: 'actions',
            header: 'Acciones',
            cell: ({ row }) => {
                return renderComponent(DataTableActions, {
                    item: row.original,
                    onSuccess,
                    canEdit,
                    canDelete,
                    dodaListBasePath
                });
            }
        }
    ];
}
