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 State = {
	m3_key: string;
	description: string;
	mex_key?: string | null;
	ame_key?: string | null;
};

export function createColumns(
	onSuccess?: () => void,
	permissions: { canEdit: boolean; canDelete: boolean } = { canEdit: true, canDelete: true }
): ColumnDef<State>[] {
	return [		
		{
			accessorKey: "m3_key",
			header: "Clave M3",
			cell: ({ row }) => {
				const keySnippet = createRawSnippet<[{ m3_key: string }]>((getKey) => {
					const { m3_key } = getKey();
					return {
						render: () =>
							`<code class="relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm font-semibold">${m3_key}</code>`
					};
				});
				return renderSnippet(keySnippet, { m3_key: row.original.m3_key });
			}
		},
		{
			accessorKey: "description",
			header: "Descripción",
			cell: ({ row }) => {
				const descSnippet = createRawSnippet<[{ description: string }]>((getDesc) => {
					const { description } = getDesc();
					return {
						render: () => `<div class="max-w-[300px] truncate">${description}</div>`
					};
				});
				return renderSnippet(descSnippet, { description: row.original.description });
			}
		},
		{
			accessorKey: "mex_key",
			header: "Clave MEX",
			cell: ({ row }) => {
				const mexSnippet = createRawSnippet<[{ mex_key?: string | null }]>((getMex) => {
					const { mex_key } = getMex();
					const content = mex_key 
						? `<code class="relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-xs">${mex_key}</code>`
						: '<span class="text-muted-foreground text-xs">-</span>';
					return {
						render: () => content
					};
				});
				return renderSnippet(mexSnippet, { mex_key: row.original.mex_key });
			}
		},
		{
			accessorKey: "ame_key",
			header: "Clave AME",
			cell: ({ row }) => {
				const ameSnippet = createRawSnippet<[{ ame_key?: string | null }]>((getAme) => {
					const { ame_key } = getAme();
					const content = ame_key 
						? `<code class="relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-xs">${ame_key}</code>`
						: '<span class="text-muted-foreground text-xs">-</span>';
					return {
						render: () => content
					};
				});
				return renderSnippet(ameSnippet, { ame_key: row.original.ame_key });
			}
		},
		{
			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();
