import type { ColumnDef } from "@tanstack/table-core";
import { renderSnippet } from "$lib/components/ui/data-table/index.js";
import { createRawSnippet } from "svelte";
import type { A76Class } from "$lib/api/dashboard/a76/classes";
import {
	formatMexTariffDigitsForDisplay,
	normalizeMexTariffDigitsStored
} from "$lib/utils/mexican-tariff-fraction";

export function createColumns(): ColumnDef<A76Class>[] {
	return [
		{
			id: "select",
			header: ({ table }) => {
				return renderSnippet(
					createRawSnippet(() => ({
						render: () => `<div class="w-4"></div>`
					}))
				);
			},
			cell: ({ row }) => {
				const isSelected = row.getIsSelected();
				const checkboxSnippet = createRawSnippet<[
					{ selected: boolean; onchange: (e: Event) => void }
				]>((getProps) => {
					const { selected, onchange } = getProps();
					return {
						render: () => `<div class="flex items-center justify-center">
							<input type="checkbox" tabindex="-1" class="h-4 w-4 rounded border-gray-300 text-primary focus:ring-primary cursor-pointer" ${selected ? 'checked' : ''} />
						</div>`,
						setup: (node) => {
							const input = node.querySelector('input') as HTMLInputElement | null;
							input?.addEventListener('change', onchange);
						}
					};
				});
				return renderSnippet(checkboxSnippet, {
					selected: isSelected,
					onchange: (e: Event) => {
						e.stopPropagation();
						const rowId = row.original.id;
						if (typeof rowId === 'number') {
							(
								row.table.options.meta as
									| { toggleSelectedId?: (id: number, checked?: boolean) => void }
									| undefined
							)?.toggleSelectedId?.(rowId, (e.target as HTMLInputElement).checked);
						}
					}
				});
			},
			size: 40,
			enableSorting: false,
			enableHiding: false
		},
		{
			accessorKey: "class_code",
			header: "Clase",
			enableSorting: true,
			cell: ({ row }) => {
				const codeSnippet = createRawSnippet<[{ code: string }]>((getProps) => {
					const { code } = getProps();
					return {
						render: () => `<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">${code}</span>`
					};
				});
				return renderSnippet(codeSnippet, { code: row.original.class_code });
			}
		},
		{
			accessorKey: "description_es",
			header: "Descripción Español",
			enableSorting: true,
			cell: ({ row }) => {
				const descSnippet = createRawSnippet<[{ desc: string | null }]>((getProps) => {
					const { desc } = getProps();
					return {
						render: () => `<div class="text-sm font-medium">${desc || ''}</div>`
					};
				});
				return renderSnippet(descSnippet, { desc: row.original.description_es });
			}
		},
		{
			accessorKey: "description_en",
			header: "Descripción Inglés",
			enableSorting: true,
			cell: ({ row }) => {
				const descSnippet = createRawSnippet<[{ desc: string | null }]>((getProps) => {
					const { desc } = getProps();
					return {
						render: () => `<div class="text-sm text-muted-foreground">${desc || ''}</div>`
					};
				});
				return renderSnippet(descSnippet, { desc: row.original.description_en });
			}
		},
		{
			accessorKey: "material_key",
			header: "Tipo",
			enableSorting: true,
			cell: ({ row }) => {
				const typeSnippet = createRawSnippet<[{ key: string | null }]>((getProps) => {
					const { key } = getProps();
					let colorClass = 'bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-400';
					if (key === 'MP') colorClass = 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400';
					else if (key === 'SC') colorClass = 'bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-400';
					else if (key === 'DESP') colorClass = 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400';
					
					return {
						render: () => `<span class="rounded-full px-2 py-0.5 text-[10px] font-bold tracking-wider uppercase ${colorClass}">${key || ''}</span>`
					};
				});
				return renderSnippet(typeSnippet, { key: row.original.material_key });
			}
		},
		{
			accessorKey: "unit_of_measure",
			header: "U.M.",
			enableSorting: true,
			cell: ({ row }) => {
				const umSnippet = createRawSnippet<[{ um: string | null }]>((getProps) => {
					const { um } = getProps();
					return {
						render: () => `<div class="text-muted-foreground">${um || ''}</div>`
					};
				});
				return renderSnippet(umSnippet, { um: row.original.unit_of_measure });
			}
		},
		{
			accessorKey: "fraction",
			header: "Fracción",
			enableSorting: true,
			cell: ({ row }) => {
				const fracSnippet = createRawSnippet<[{ fr: string | null }]>((getProps) => {
					const { fr } = getProps();
					return {
						render: () => `<span class="font-mono text-xs text-orange-600 dark:text-orange-400">${fr || ''}</span>`
					};
				});
				const ext = row.original as A76Class & { import_tariff_code?: string | null };
				const fr = formatMexTariffDigitsForDisplay(
					normalizeMexTariffDigitsStored(ext.import_tariff_code || ext.fraction || '')
				);
				return renderSnippet(fracSnippet, { fr });
			}
		},
		{
			accessorKey: "us_fraction",
			header: "Fracción US",
			enableSorting: true,
			cell: ({ row }) => {
				const fracSnippet = createRawSnippet<[{ fr: string | null }]>((getProps) => {
					const { fr } = getProps();
					return {
						render: () => `<span>${fr || '-'}</span>`
					};
				});
				return renderSnippet(fracSnippet, { fr: row.original.us_fraction });
			}
		}
	];
}

export const columns = createColumns();
