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 { Invoice } from '$lib/api/dashboard/a76/invoices';
import { getInvoiceTypeColor } from "$lib/utils";

function formatDate(date?: string | null): string {
	if (!date) return '-';
	return new Date(date).toLocaleDateString('es-MX', {
		year: 'numeric',
		month: '2-digit',
		day: '2-digit'
	});
}

export function createColumns(
	onSuccess?: () => void
): ColumnDef<Invoice>[] {
	return [
		// 0. NUEVA COLUMNA: Checkbox visual (el estado real lo maneja la opacidad)
		{
			id: "select",
			header: ({ table }) => {
				return renderSnippet(
					createRawSnippet(() => ({
						render: () => `<div class="w-4"></div>`
					}))
				);
			},
			cell: ({ row }) => {
				const isSelected = row.getIsSelected();

				const checkboxSnippet = createRawSnippet<[{ selected: boolean }]>((getProps) => {
					const { selected } = getProps();
					return {
						render: () => `<div class="flex items-center justify-center">
							<input type="checkbox" class="h-4 w-4" ${selected ? 'checked' : ''} />
						</div>`
					};
				});

				return renderSnippet(checkboxSnippet, { selected: isSelected });
			},
			enableSorting: false,
			enableHiding: false,
		},
		{
			accessorKey: "operation_type",
			header: "Operación",
			cell: ({ row }) => {
				const operationType = row.original.operation_type;

				const operationSnippet = createRawSnippet<[{ type?: string | null }]>((getType) => {
					const { type } = getType();
					const isImport = type === 'imp';
					const colorClass = isImport ? 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200' : 'bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200';
					const label = isImport ? 'Importación' : type === 'exp' ? 'Exportación' : '-';
					return {
						render: () =>
							`<span class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${colorClass}">
                                ${label}
                            </span>`
					};
				});
				return renderSnippet(operationSnippet, { type: operationType });
			}
		},
		{
			accessorKey: "invoice_type",
			header: "Tipo Factura",
			cell: ({ row }) => {
				const invoiceType = row.original.invoice_type;
				const colorClass = getInvoiceTypeColor(invoiceType);

				const typeSnippet = createRawSnippet<[{ type?: string | null; colorClass: string }]>((getProps) => {
					const { type, colorClass } = getProps();
					return {
						render: () =>
							`<span class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${colorClass}">
                                ${type || '-'}
                            </span>`
					};
				});
				return renderSnippet(typeSnippet, { type: invoiceType, colorClass });
			}
		},
		{
			accessorKey: "invoice_number",
			header: "Núm. Factura",
			cell: ({ row }) => {
				const numberSnippet = createRawSnippet<[{ number?: string | null }]>((getNumber) => {
					const { number } = getNumber();
					return {
						render: () =>
							`<code class="relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm font-semibold">${number || 'N/A'}</code>`
					};
				});
				return renderSnippet(numberSnippet, { number: row.original.invoice_number });
			}
		},
		{
			accessorKey: "compliance_mx.pedimento",
			header: "Pedimento 18",
			cell: ({ row }) => {
				const pedimento = row.original.compliance_mx?.pedimento;
				const fullNumber = pedimento
					? `${pedimento.year || ''}-${pedimento.customs_office || ''}-${pedimento.license || ''}-${pedimento.pedimento_number || ''}`
					: null;

				const pedimentoSnippet = createRawSnippet<[{ number?: string | null }]>((getPedimento) => {
					const { number } = getPedimento();
					return {
						render: () =>
							`<code class="relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm font-semibold">${number || 'N/A'}</code>`
					};
				});
				return renderSnippet(pedimentoSnippet, { number: fullNumber });
			}
		},
		{
			accessorKey: "compliance_mx.remesa",
			header: "Remesa",
			cell: ({ row }) => {
				const remesa = row.original.compliance_mx?.remesa;

				const remesaSnippet = createRawSnippet<[{ remesa?: number | null }]>((getRemesa) => {
					const { remesa } = getRemesa();
					return {
						render: () =>
							`<div class="text-sm">${remesa || '-'}</div>`
					};
				});
				return renderSnippet(remesaSnippet, { remesa });
			}
		},
		{
			accessorKey: "invoice_date",
			header: "Fecha Factura",
			cell: ({ row }) => {
				const dateSnippet = createRawSnippet<[{ date: string }]>((getDate) => {
					const { date } = getDate();
					return {
						render: () =>
							`<div class="text-sm text-muted-foreground">${date}</div>`
					};
				});
				return renderSnippet(dateSnippet, { date: formatDate(row.original.invoice_date) });
			}
		},
		{
			accessorKey: "compliance_mx.pedimento.pedimento_code",
			header: "Clave Ped.",
			cell: ({ row }) => {
				const pedimentoCode = row.original.compliance_mx?.pedimento?.pedimento_code;

				const claveSnippet = createRawSnippet<[{ code?: string }]>((getClave) => {
					const { code } = getClave();
					return {
						render: () =>
							`<div class="text-sm font-medium">${code || '-'}</div>`
					};
				});
				return renderSnippet(claveSnippet, { code: pedimentoCode });
			}
		},
		{
			accessorKey: "document_type",
			header: "Tipo Doc.",
			cell: ({ row }) => {
				const typeSnippet = createRawSnippet<[{ type?: string | null }]>((getType) => {
					const { type } = getType();
					return {
						render: () =>
							`<div class="text-sm capitalize">${type || '-'}</div>`
					};
				});
				return renderSnippet(typeSnippet, { type: row.original.document_type });
			}
		},
		{
			accessorKey: "total_items",
			header: "Total Partidas",
			cell: ({ row }) => {
				const totalItems = row.original.details?.length || 0;

				const itemsSnippet = createRawSnippet<[{ total: number }]>((getTotal) => {
					const { total } = getTotal();
					return {
						render: () =>
							`<div class="text-sm text-center">${total}</div>`
					};
				});
				return renderSnippet(itemsSnippet, { total: totalItems });
			}
		},
		{
			accessorKey: "financials.currency",
			header: "Moneda",
			cell: ({ row }) => {
				const currency = row.original.financials?.currency;

				const currencySnippet = createRawSnippet<[{ currency?: string | null }]>((getCurrency) => {
					const { currency } = getCurrency();
					return {
						render: () =>
							`<div class="text-sm font-medium">${currency?.toLocaleUpperCase() || '-'}</div>`
					};
				});
				return renderSnippet(currencySnippet, { currency });
			}
		},
		{
			accessorKey: "financials.currency_type",
			header: "Tipo Moneda",
			cell: ({ row }) => {
				const currencyType = row.original.financials?.currency_type;

				const typeSnippet = createRawSnippet<[{ type?: string | null }]>((getType) => {
					const { type } = getType();
					return {
						render: () =>
							`<div class="text-sm">${type || '-'}</div>`
					};
				});
				return renderSnippet(typeSnippet, { type: currencyType });
			}
		},
		{
			accessorKey: "logistics.weight_type",
			header: "Tipo Peso",
			cell: ({ row }) => {
				const weightType = row.original.logistics?.weight_type;

				const weightSnippet = createRawSnippet<[{ type?: string | null }]>((getType) => {
					const { type } = getType();
					return {
						render: () =>
							`<div class="text-sm">${type?.toUpperCase() || '-'}</div>`
					};
				});
				return renderSnippet(weightSnippet, { type: weightType });
			}
		},
		{
			accessorKey: "is_updated",
			header: "Actualizado",
			cell: ({ row }) => {
				const isUpdated = row.original.is_updated;

				const updatedSnippet = createRawSnippet<[{ isUpdated?: boolean | null }]>((getUpdated) => {
					const { isUpdated } = getUpdated();
					const colorClass = isUpdated ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800';
					const label = isUpdated ? 'Sí' : 'No';
					return {
						render: () =>
							`<span class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${colorClass}">
                                ${label}
                            </span>`
					};
				});
				return renderSnippet(updatedSnippet, { isUpdated });
			}
		},
		{
			accessorKey: "compliance_mx.is_mixed",
			header: "Mixto",
			cell: ({ row }) => {
				const isMixed = row.original.compliance_mx?.is_mixed;

				const mixedSnippet = createRawSnippet<[{ isMixed?: boolean | null }]>((getMixed) => {
					const { isMixed } = getMixed();
					const colorClass = isMixed ? 'bg-blue-100 text-blue-800' : 'bg-gray-100 text-gray-800';
					const label = isMixed ? 'Sí' : 'No';
					return {
						render: () =>
							`<span class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${colorClass}">
                                ${label}
                            </span>`
					};
				});
				return renderSnippet(mixedSnippet, { isMixed });
			}
		},
		{
			accessorKey: "related_doc_id",
			header: "Doc. Relacionado",
			cell: ({ row }) => {
				const relDoc = row.original.related_doc_id;

				const relDocSnippet = createRawSnippet<[{ relDoc?: number | null }]>((getRelDoc) => {
					const { relDoc } = getRelDoc();
					return {
						render: () =>
							`<div class="text-sm">${relDoc || '-'}</div>`
					};
				});
				return renderSnippet(relDocSnippet, { relDoc });
			}
		},
		// 2. MODIFICAMOS AQUÍ: Pasamos onDownload al componente
		{
			id: "actions",
			cell: ({ row }) => {
				return renderComponent(DataTableActions, {
					invoice: row.original,
					onSuccess
				});
			}
		}
	];
}


export const columns = createColumns();