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";

/**
 * 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 function createColumns(onSuccess?: () => void): ColumnDef<Part>[] {
    return [

        {
            accessorKey: "is_active",
            header: "Status",
            cell: ({ row }) => {
                const statusSnippet = createRawSnippet<[{ active: boolean }]>((getStatus) => {
                    const { active } = getStatus();
                    return {
                        render: () => active 
                            ? `<span class="inline-flex items-center rounded-full bg-green-50 px-2 py-1 text-xs font-medium text-green-700 ring-1 ring-inset ring-green-600/20">Activo</span>`
                            : `<span class="inline-flex items-center rounded-full bg-red-50 px-2 py-1 text-xs font-medium text-red-700 ring-1 ring-inset ring-red-600/10">Inactivo</span>`
                    };
                });
                return renderSnippet(statusSnippet, { active: row.original.is_active });
            }
        },

    
        {
            accessorKey: "part_number",
            header: "No. Parte",
            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",
            cell: ({ row }) => {
                const descSnippet = createRawSnippet<[{ desc: string }]>((getDesc) => {
                    const { desc } = getDesc();
                    return {
                        render: () =>
                            `<div class="max-w-[250px] truncate text-xs font-medium uppercase text-muted-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-xs text-muted-foreground/70" title="${desc}">${desc || '-'}</div>`
                    };
                });
                return renderSnippet(descEnSnippet, { desc: row.original.description_english || '' });
            }
        },

    
        {
            accessorKey: "part_class",
            header: "Clase",
            cell: ({ row }) => {
                const classSnippet = createRawSnippet<[{ cls: string }]>((getCls) => {
                    const { cls } = getCls();
                    return {
                        render: () => `<div class="text-xs font-mono">${cls || '-'}</div>`
                    };
                });
                return renderSnippet(classSnippet, { cls: row.original.part_class || '' });
            }
        },

      
        {
            accessorKey: "commercial_part_number", 
            header: "Tipo",
            cell: ({ row }) => {
                const typeSnippet = createRawSnippet<[{ val: string }]>((getType) => {
                    const { val } = getType();
                    return {
                        render: () => `<div class="text-xs text-muted-foreground">${val || '-'}</div>`
                    };
                });
                return renderSnippet(typeSnippet, { val: row.original.commercial_part_number || '' });
            }
        },

        // 7. U.M. (Unidad de Medida)
        {
            accessorKey: "unit_of_measure",
            header: "U.M.",
            cell: ({ row }) => {
                const umSnippet = createRawSnippet<[{ um: string }]>((getUm) => {
                    const { um } = getUm();
                    return {
                        render: () =>
                            `<span class="inline-flex items-center rounded-sm bg-blue-50 dark:bg-blue-900 text-blue-700 dark:text-blue-300 px-1.5 py-0.5 text-[10px] font-bold ring-1 ring-inset ring-blue-700/10">
                                ${um}
                            </span>`
                    };
                });
                return renderSnippet(umSnippet, { um: row.original.unit_of_measure });
            }
        },

        // 8. FRACCION
        {
            accessorKey: "fraction",
            header: "Fracción",
            cell: ({ row }) => {
                const fracSnippet = createRawSnippet<[{ fr: string }]>((getFrac) => {
                    const { fr } = getFrac();
                    return {
                        render: () => `<span class="font-mono text-xs bg-slate-100 dark:bg-slate-800 px-1.5 py-0.5 rounded">${fr || '-'}</span>`
                    };
                });
                return renderSnippet(fracSnippet, { fr: row.original.fraction || '' });
            }
        },

        // 9. U.M.T. (del inv_data)
        {
            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">${umt || '-'}</div>`
                    };
                });
                return renderSnippet(umtSnippet, { umt: row.original.inv_data?.stock_uom || '' });
            }
        },

        // 10. COSTO
        {
            accessorKey: "unit_cost",
            header: "Costo",
            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">${formatCurrency(amount, curr)}</div>`
                    };
                });
                return renderSnippet(costSnippet, { 
                    amount: row.original.unit_cost, 
                    curr: row.original.currency_key 
                });
            }
        },

        // 11. MONEDA
        {
            accessorKey: "currency_key",
            header: "Moneda",
            cell: ({ row }) => {
                const currSnippet = createRawSnippet<[{ curr: string }]>((getCurr) => {
                    const { curr } = getCurr();
                    return {
                        render: () => `<span class="inline-flex items-center rounded-sm bg-emerald-50 dark:bg-emerald-900 text-emerald-700 dark:text-emerald-300 px-1.5 py-0.5 text-[10px] font-bold">${curr || '-'}</span>`
                    };
                });
                return renderSnippet(currSnippet, { curr: row.original.currency_key || '' });
            }
        },

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

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

        // 14. FECHA MODIFICACIÓN
        {
            accessorKey: "updated_at",
            header: "Fecha Modificación",
            cell: ({ row }) => {
                const dateSnippet = createRawSnippet<[{ date: string }]>((getDate) => {
                    const { date } = getDate();
                    if (!date) return { render: () => '-' };
                    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 });
            }
        }
    ];
}

export const columns = createColumns();