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 Sector = {
	id: number;
	key: string;
	description: string;
	authorized: boolean;
	company_id: number;
	tenant_id: number;
};

export function createColumns(
	onSuccess?: () => void,
	permissions: { canEdit: boolean; canDelete: boolean } = { canEdit: true, canDelete: true }
): ColumnDef<Sector>[] {
	return [		
		{
			accessorKey: "key",
			header: "Clave",
			cell: ({ row }) => {
				const keySnippet = createRawSnippet<[{ key: string }]>((getKey) => {
					const { key } = getKey();
					return {
						render: () =>
							`<code class="relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm font-semibold">${key}</code>`
					};
				});
				return renderSnippet(keySnippet, { key: row.original.key });
			}
		},
		{
			accessorKey: "description",
			header: "Descripción",
			cell: ({ row }) => {
				const descSnippet = createRawSnippet<[{ description: string }]>((getDesc) => {
					const { description } = getDesc();
					return {
						render: () => `<div class="max-w-[500px] truncate">${description}</div>`
					};
				});
				return renderSnippet(descSnippet, { description: row.original.description });
			}
		},
		{
			accessorKey: "authorized",
			header: "Autorizado",
			cell: ({ row }) => {
				const authSnippet = createRawSnippet<[{ authorized: boolean }]>((getAuth) => {
					const { authorized } = getAuth();
					const badge = authorized
						? '<span class="inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200">Sí</span>'
						: '<span class="inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200">No</span>';
					return {
						render: () => badge
					};
				});
				return renderSnippet(authSnippet, { authorized: row.original.authorized });
			}
		},
		{
			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();
