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

export type CodePedimentoRegimen = {
	id: number;
	pedimento_code: string;
	regimen_code: string | null;
	type_code: string | null;
};

export function createColumns(
	onSuccess?: () => void,
	permissions: { canEdit: boolean; canDelete: boolean } = { canEdit: true, canDelete: true }
): ColumnDef<CodePedimentoRegimen>[] {
	return [
		{
			accessorKey: "pedimento_code",
			header: "Código Pedimento",
			cell: ({ row }) => {
				const codeSnippet = createRawSnippet<[{ code: string }]>((getCode) => {
					const { code } = getCode();
					return {
						render: () =>
							`<code class="relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm">${code}</code>`
					};
				});
				return renderSnippet(codeSnippet, { code: row.original.pedimento_code });
			}
		},
		{
			accessorKey: "regimen_code",
			header: "Código Régimen",
			cell: ({ row }) => {
				const regimenSnippet = createRawSnippet<[{ code: string | null }]>((getCode) => {
					const { code } = getCode();
					if (code) {
						return {
							render: () =>
								`<code class="relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm">${code}</code>`
						};
					}
					return {
						render: () => `<span class="text-muted-foreground">N/A</span>`
					};
				});
				return renderSnippet(regimenSnippet, { code: row.original.regimen_code });
			}
		},
		{
			accessorKey: "type_code",
			header: "Tipo",
			cell: ({ row }) => {
				const typeSnippet = createRawSnippet<[{ type: string | null }]>((getType) => {
					const { type } = getType();
					if (type) {
						return {
							render: () =>
								`<span class="inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2">${type}</span>`
						};
					}
					return {
						render: () => `<span class="text-muted-foreground">N/A</span>`
					};
				});
				return renderSnippet(typeSnippet, { type: row.original.type_code });
			}
		},
		{
			id: "actions",
			cell: ({ row }) => {
				return renderComponent(DataTableActions, {
					item: row.original,
					onSuccess,
					canEdit: permissions.canEdit,
					canDelete: permissions.canDelete
				});
			}
		}
	];
}

// Mantener compatibilidad hacia atrás
export const columns = createColumns();
