<script lang="ts" generics="TData, TValue">
	import { type ColumnDef, getCoreRowModel } from '@tanstack/table-core';
	import { createSvelteTable, FlexRender } from '$lib/components/ui/data-table/index.js';
	import * as Table from '$lib/components/ui/table/index.js';

	type DataTableProps<TData, TValue> = {
		columns: ColumnDef<TData, TValue>[];
		data: TData[];
		onRowClick?: (row: TData) => void;
	onRowDoubleClick?: (row: TData) => void;
		selectedId?: string | number | null;
		idField?: keyof TData;
	};

let {
	data,
	columns,
	onRowClick,
	onRowDoubleClick,
	selectedId,
	idField
}: DataTableProps<TData, TValue> = $props();

	const table = $derived(
		createSvelteTable({
			data,
			columns,
			getCoreRowModel: getCoreRowModel()
		})
	);
</script>

<div class="w-full">
	<div class="rounded-md border">
		<Table.Root>
			<Table.Header>
				{#each table.getHeaderGroups() as headerGroup (headerGroup.id)}
					<Table.Row>
						{#each headerGroup.headers as header (header.id)}
							<Table.Head>
								{#if !header.isPlaceholder}
									<FlexRender
										content={header.column.columnDef.header}
										context={header.getContext()}
									/>
								{/if}
							</Table.Head>
						{/each}
					</Table.Row>
				{/each}
			</Table.Header>

			<Table.Body>
				{#each table.getRowModel().rows as row (row.id)}
					<Table.Row
						onclick={() => onRowClick?.(row.original)}
						ondblclick={() => onRowDoubleClick?.(row.original)}
						class="cursor-pointer transition-colors hover:bg-muted/50 {selectedId &&
						idField &&
						row.original[idField] === selectedId
							? 'bg-muted'
							: ''}"
					>
						{#each row.getVisibleCells() as cell (cell.id)}
							<Table.Cell>
								<FlexRender content={cell.column.columnDef.cell} context={cell.getContext()} />
							</Table.Cell>
						{/each}
					</Table.Row>
				{:else}
					<Table.Row>
						<Table.Cell colspan={columns.length} class="h-24 text-center">
							No hay resultados.
						</Table.Cell>
					</Table.Row>
				{/each}
			</Table.Body>
		</Table.Root>
	</div>
</div>
