import type { ColumnDef } from "@tanstack/table-core";
import { renderComponent, renderSnippet } from "$lib/components/ui/data-table/index.js";
import { createRawSnippet } from "svelte";
import DataTableActions from "./data-table-actions.svelte";
import type { Part } from "$lib/api/dashboard/a76/parts";
import { formatMexTariffDigitsForDisplay } from "$lib/utils/mexican-tariff-fraction";
import { Checkbox } from "$lib/components/ui/checkbox/index.js";

/**
 * Formatea moneda (USD/MXN)
 */
function formatCurrency(amount: number | null, currency: string | null): string {
    if (amount === null || amount === undefined) return '-';
    return new Intl.NumberFormat('en-US', {
        style: 'currency',
        currency: currency || 'USD',
        minimumFractionDigits: 4
    }).format(amount);
}

export type GoodsPartsColumnOptions = {
    canEdit?: boolean;
    canDelete?: boolean;
};

export function createColumns(
    onSuccess?: () => void,
    options: GoodsPartsColumnOptions = {}
): ColumnDef<Part>[] {
    const { canEdit = false, canDelete = false } = options;
    return [
        {
            id: "select",
            header: "", // Cabecera vacía para igualar a Clases
            cell: ({ row }) => {
                return renderComponent(Checkbox, {
                    checked: row.getIsSelected(),
                    onCheckedChange: (value) => row.toggleSelected(!!value),
                    "aria-label": "Select row"
                });
            },
            size: 40,
            enableSorting: false,
            enableHiding: false
        },

        {
            accessorKey: "is_active",
            header: "Status",
            enableSorting: true,
            cell: ({ row }) => {
                const statusSnippet = createRawSnippet<[{ active: boolean }]>((getStatus) => {
                    const { active } = getStatus();
                    return {
                        render: () => active
                            ? `<span class="inline-flex items-center rounded-full bg-green-100 px-2 py-0.5 text-[10px] font-bold uppercase text-green-700 dark:bg-green-900/30 dark:text-green-400">Activo</span>`
                            : `<span class="inline-flex items-center rounded-full bg-red-100 px-2 py-0.5 text-[10px] font-bold uppercase text-red-700 dark:bg-red-900/30 dark:text-red-400">Inactivo</span>`
                    };
                });
                return renderSnippet(statusSnippet, { active: row.original.is_active });
            }
        },

        {
            accessorKey: "part_number",
            header: "No. Parte",
            enableSorting: true,
            cell: ({ row }) => {
                const pnSnippet = createRawSnippet<[{ pn: string }]>((getPn) => {
                    const { pn } = getPn();
                    return {
                        render: () =>
                            `<div class="font-mono text-sm font-semibold text-foreground whitespace-nowrap">${pn}</div>`
                    };
                });
                return renderSnippet(pnSnippet, { pn: row.original.part_number });
            }
        },

        {
            accessorKey: "description_spanish",
            header: "Descripción",
            enableSorting: true,
            cell: ({ row }) => {
                const descSnippet = createRawSnippet<[{ desc: string }]>((getDesc) => {
                    const { desc } = getDesc();
                    return {
                        render: () =>
                            `<div class="max-w-[250px] truncate text-sm font-medium text-foreground" title="${desc}">${desc || '-'}</div>`
                    };
                });
                return renderSnippet(descSnippet, { desc: row.original.description_spanish || '' });
            }
        },

        {
            accessorKey: "description_english",
            header: "Desc. Inglés",
            cell: ({ row }) => {
                const descEnSnippet = createRawSnippet<[{ desc: string }]>((getDesc) => {
                    const { desc } = getDesc();
                    return {
                        render: () =>
                            `<div class="max-w-[200px] truncate text-sm text-muted-foreground" title="${desc}">${desc || '-'}</div>`
                    };
                });
                return renderSnippet(descEnSnippet, { desc: row.original.description_english || '' });
            }
        },

        // CLASE - Estilo de Clases (borde azul)
        {
            accessorKey: "part_class",
            header: "Clase",
            enableSorting: true,
            cell: ({ row }) => {
                const classSnippet = createRawSnippet<[{ cls: string }]>((getCls) => {
                    const { cls } = getCls();
                    return {
                        render: () => cls
                            ? `<span class="inline-flex items-center rounded-md border border-blue-200 bg-blue-50 px-2 py-1 font-mono text-xs font-bold text-blue-700 dark:border-blue-800 dark:bg-blue-900/30 dark:text-blue-400">${cls}</span>`
                            : `<span class="text-xs text-muted-foreground">-</span>`
                    };
                });
                return renderSnippet(classSnippet, { cls: row.original.part_class || '' });
            }
        },

        // TIPO - Estilo de Clases (píldora oscura)
        {
            accessorKey: "commercial_part_number",
            header: "Tipo",
            cell: ({ row }) => {
                const typeSnippet = createRawSnippet<[{ val: string }]>((getType) => {
                    const { val } = getType();
                    return {
                        render: () => val
                            ? `<span class="rounded-full bg-slate-100 px-2 py-0.5 text-[10px] font-bold tracking-wider uppercase text-slate-700 dark:bg-slate-800 dark:text-slate-400">${val}</span>`
                            : `<span class="text-xs text-muted-foreground">-</span>`
                    };
                });
                return renderSnippet(typeSnippet, { val: row.original.commercial_part_number || '' });
            }
        },

        // U.M. - Estilo de Clases (texto plano claro)
        {
            accessorKey: "unit_of_measure",
            header: "U.M.",
            cell: ({ row }) => {
                const umSnippet = createRawSnippet<[{ um: string | null }]>((getUm) => {
                    const { um } = getUm();
                    return {
                        render: () => `<div class="text-sm text-muted-foreground">${um || '-'}</div>`
                    };
                });
                return renderSnippet(umSnippet, { um: row.original.unit_of_measure });
            }
        },

        // FRACCION - Estilo de Clases (texto naranja)
        {
            accessorKey: "fraction",
            header: "Fracción",
            enableSorting: true,
            cell: ({ row }) => {
                const fracSnippet = createRawSnippet<[{ fr: string }]>((getFrac) => {
                    const { fr } = getFrac();
                    return {
                        render: () => `<span class="font-mono text-xs text-orange-600 dark:text-orange-400">${fr || '-'}</span>`
                    };
                });
                return renderSnippet(fracSnippet, {
                    fr: formatMexTariffDigitsForDisplay(row.original.fraction || '')
                });
            }
        },

        // U.M.T.
        {
            id: "stock_uom",
            header: "U.M.T.",
            cell: ({ row }) => {
                const umtSnippet = createRawSnippet<[{ umt: string }]>((getUmt) => {
                    const { umt } = getUmt();
                    return {
                        render: () => `<div class="text-xs font-mono text-muted-foreground">${umt || '-'}</div>`
                    };
                });
                return renderSnippet(umtSnippet, { umt: row.original.inv_data?.stock_uom || '' });
            }
        },

        // COSTO - Texto plano
        {
            accessorKey: "unit_cost",
            header: "Costo",
            enableSorting: true,
            cell: ({ row }) => {
                const costSnippet = createRawSnippet<[{ amount: number | null, curr: string | null }]>((getCost) => {
                    const { amount, curr } = getCost();
                    return {
                        render: () => `<div class="font-mono text-xs font-medium text-foreground">${formatCurrency(amount, curr)}</div>`
                    };
                });
                return renderSnippet(costSnippet, {
                    amount: row.original.unit_cost,
                    curr: row.original.currency_key
                });
            }
        },

        // MONEDA - Texto plano para igualar el estilo minimalista
        {
            accessorKey: "currency_key",
            header: "Moneda",
            cell: ({ row }) => {
                const currSnippet = createRawSnippet<[{ curr: string }]>((getCurr) => {
                    const { curr } = getCurr();
                    return {
                        render: () => `<span class="text-[10px] font-bold text-emerald-600 dark:text-emerald-400">${curr || '-'}</span>`
                    };
                });
                return renderSnippet(currSnippet, { curr: row.original.currency_key || '' });
            }
        },

        // PESO UNITARIO
        {
            accessorKey: "unit_weight",
            header: "Peso Unitario",
            enableSorting: true,
            cell: ({ row }) => {
                const weightSnippet = createRawSnippet<[{ weight: number | null, type: string | null }]>((getWeight) => {
                    const { weight, type } = getWeight();
                    return {
                        render: () => {
                            if (weight === null || weight === undefined) return '<span class="text-muted-foreground">-</span>';
                            return `<div class="text-xs font-mono text-muted-foreground">${Number(weight).toFixed(4)} ${type || ''}</div>`;
                        }
                    };
                });
                return renderSnippet(weightSnippet, {
                    weight: row.original.unit_weight,
                    type: row.original.weight_type
                });
            }
        },

        // U.M. EXIST 
        {
            id: "equivalent_uom",
            header: "U.M. Exist",
            cell: ({ row }) => {
                const eqUomSnippet = createRawSnippet<[{ uom: string }]>((getUom) => {
                    const { uom } = getUom();
                    return {
                        render: () => `<div class="text-xs text-muted-foreground">${uom || '-'}</div>`
                    };
                });
                return renderSnippet(eqUomSnippet, { uom: row.original.inv_data?.equivalent_uom || '' });
            }
        },

        // FECHA MODIFICACIÓN
        {
            accessorKey: "updated_at",
            header: "Fecha Modificación",
            enableSorting: true,
            cell: ({ row }) => {
                const dateSnippet = createRawSnippet<[{ date: string }]>((getDate) => {
                    const { date } = getDate();
                    if (!date) return { render: () => '<span class="text-muted-foreground">-</span>' };
                    const formatted = new Date(date).toLocaleDateString('es-MX', {
                        year: 'numeric',
                        month: '2-digit',
                        day: '2-digit'
                    });
                    return {
                        render: () => `<div class="text-xs text-muted-foreground">${formatted}</div>`
                    };
                });
                return renderSnippet(dateSnippet, { date: row.original.updated_at });
            }
        },

        // ACCIONES
        {
            id: "actions",
            header: "",
            cell: ({ row }) => {
                return renderComponent(DataTableActions, {
                    item: row.original,
                    onSuccess,
                    canEdit,
                    canDelete
                });
            }
        }
    ];
}