import type { ExpedienteArchivo } from '$lib/api/dashboard/a76/expediente-archivos';
import type { ColumnDef } from '@tanstack/table-core';
import { createRawSnippet } from 'svelte';
import { renderComponent, renderSnippet } from '$lib/components/ui/data-table';
import DataTableActions from './data-table-actions.svelte';
import EDocumentCell from './e-document-cell.svelte';

function formatDate(dateStr?: string | null): string {
	if (!dateStr) return '-';
	const raw = String(dateStr);
	const ymd = raw.includes('T') ? raw.split('T')[0] : raw;
	const parts = ymd.split('-').map(Number);
	if (parts.length === 3 && parts.every((part) => Number.isFinite(part))) {
		const [year, month, day] = parts;
		return new Date(year, month - 1, day).toLocaleDateString('es-MX', {
			day: '2-digit',
			month: '2-digit',
			year: 'numeric'
		});
	}
	return new Date(raw).toLocaleDateString('es-MX', {
		day: '2-digit',
		month: '2-digit',
		year: 'numeric'
	});
}

export function createColumns(
	onSuccess?: () => void,
	onDigitalizar?: (item: ExpedienteArchivo) => void,
	onAcuse?: (item: ExpedienteArchivo) => void
): ColumnDef<ExpedienteArchivo>[] {
	return [
		{
			id: 'select',
			header: ({ table }) => {
				const isAllSelected = table.getIsAllPageRowsSelected();
				const isSomeSelected = table.getIsSomePageRowsSelected();

				const selectAllSnippet = createRawSnippet<[
					{ checked: boolean; indeterminate: boolean; onchange: (event: Event) => void }
				]>((getProps) => {
					const { checked, indeterminate, onchange } = getProps();
					return {
						render: () => `<div class="w-4">
							<input
								type="checkbox"
								tabindex="-1"
								class="h-4 w-4 cursor-pointer"
								${checked ? 'checked' : ''}
								${indeterminate ? 'indeterminate="true"' : ''}
							/>
						</div>`,
						setup: (node) => {
							const input = node.querySelector('input') as HTMLInputElement | null;
							if (!input) return;
							input.indeterminate = indeterminate;
							input.addEventListener('change', onchange);
						}
					};
				});

				return renderSnippet(selectAllSnippet, {
					checked: isAllSelected,
					indeterminate: isSomeSelected && !isAllSelected,
					onchange: (event: Event) => {
						table.toggleAllPageRowsSelected(!!(event.target as HTMLInputElement).checked);
					}
				});
			},
			cell: ({ row }) => {
				const checkboxSnippet = createRawSnippet<[
					{ selected: boolean; onchange: (event: 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 cursor-pointer" ${selected ? 'checked' : ''} />
						</div>`,
						setup: (node) => {
							const input = node.querySelector('input') as HTMLInputElement | null;
							if (!input) return;
							input.addEventListener('click', (event) => event.stopPropagation());
							input.addEventListener('change', onchange);
						}
					};
				});

				return renderSnippet(checkboxSnippet, {
					selected: row.getIsSelected(),
					onchange: (event: Event) => {
						event.stopPropagation();
						row.toggleSelected(!!(event.target as HTMLInputElement).checked);
					}
				});
			},
			enableSorting: false,
			enableHiding: false
		},
		{
			accessorKey: 'id',
			header: 'Consecutivo',
			cell: ({ row }) => row.original.id
		},
		{
			accessorKey: 'tipo_documento',
			header: 'Tipo Documento',
			cell: ({ row }) => row.original.tipo_documento || '-'
		},
		{
			accessorKey: 'rfc_consulta',
			header: 'RFC Consulta',
			cell: ({ row }) => row.original.rfc_consulta || '-'
		},
		{
			accessorKey: 'nombre_archivo',
			header: 'Archivo',
			cell: ({ row }) => row.original.nombre_archivo || '-'
		},
		{
			accessorKey: 'e_document',
			header: 'E-Document',
			cell: ({ row }) => renderComponent(EDocumentCell, { item: row.original })
		},
		{
			accessorKey: 'fecha_digitalizacion',
			header: 'Fecha',
			cell: ({ row }) => formatDate(row.original.fecha_digitalizacion)
		},
		{
			accessorKey: 'num_operacion',
			header: 'Núm. Operación VU',
			cell: ({ row }) => row.original.num_operacion || '-'
		},
		{
			id: 'actions',
			header: 'Acciones',
			size: 88,
			cell: ({ row }) =>
				renderComponent(DataTableActions, {
					item: row.original,
					onSuccess,
					onDigitalizar,
					onAcuse
				})
		}
	];
}
