<script lang="ts" generics="TData, TValue">
	import { onMount } from 'svelte';
	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[];
		loading: boolean;
		hasMore: boolean;
		loadMore: () => void;
		// Props para selección
		selectedIds?: number[];
		onRowClick?: (row: TData) => void;
		compact?: boolean;
	};

	let {
		data,
		columns,
		loading,
		hasMore,
		loadMore,
		selectedIds = [],
		onRowClick,
		compact = false
	}: DataTableProps<TData, TValue> = $props();

	const table = createSvelteTable({
		get data() {
			return data;
		},
		columns,
		getCoreRowModel: getCoreRowModel(),
		getRowId: (row: any) => row.id?.toString(), // Usar ID para identificar filas
		state: {
			get rowSelection() {
				// Mapear los IDs seleccionados al formato que espera TanStack Table
				const selection: Record<string, boolean> = {};
				selectedIds.forEach((id) => {
					selection[id.toString()] = true;
				});
				return selection;
			}
		},
		enableRowSelection: true,
		enableMultiRowSelection: true

		// No necesitamos onRowSelectionChange porque controlamos el estado desde fuera
	});

	let scrollContainer = $state<HTMLDivElement>();
	let loadingTrigger = $state<HTMLDivElement>();

	// Intersection Observer para detectar cuando el usuario llega al final
	onMount(() => {
		const observer = new IntersectionObserver(
			(entries) => {
				const [entry] = entries;
				if (entry.isIntersecting && hasMore && !loading) {
					loadMore();
				}
			},
			{
				root: scrollContainer,
				threshold: 0.1
			}
		);

		if (loadingTrigger) {
			observer.observe(loadingTrigger);
		}

		return () => {
			observer.disconnect();
		};
	});
</script>

<div class="w-full">
	<div class="max-h-[600px] overflow-y-auto rounded-md border" bind:this={scrollContainer}>
		<Table.Root>
			<Table.Header class="bg-background">
				{#each table.getHeaderGroups() as headerGroup (headerGroup.id)}
					{@const headerList = headerGroup.headers}
					{@const lastHeaderColId = headerList[headerList.length - 1]?.column.id}
					<Table.Row>
						{#each headerList as header (header.id)}
							{@const colId = header.column.id}
							<Table.Head
								class={[
									colId === 'select' &&
										'sticky left-0 z-40 min-w-[2.75rem] border-r border-border/70 bg-background shadow-[4px_0_12px_-6px_rgba(0,0,0,0.12)] dark:shadow-[4px_0_12px_-6px_rgba(0,0,0,0.35)]',
									colId === lastHeaderColId &&
										'sticky right-0 z-40 border-l border-border/70 bg-background shadow-[-4px_0_12px_-6px_rgba(0,0,0,0.12)] dark:shadow-[-4px_0_12px_-6px_rgba(0,0,0,0.35)]'
								]
									.filter(Boolean)
									.join(' ')}
							>
								{#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)}
					{@const visibleCells = row.getVisibleCells()}
					{@const lastCellColId = visibleCells[visibleCells.length - 1]?.column.id}
					<Table.Row
						data-state={row.getIsSelected() && 'selected'}
						class="group/inv-list cursor-pointer transition-colors {row.getIsSelected()
							? 'bg-gray-300 dark:bg-gray-600'
							: 'hover:bg-gray-100 dark:hover:bg-gray-700'}"
						onclick={() => onRowClick && onRowClick(row.original)}
					>
						{#each visibleCells as cell (cell.id)}
							{@const colId = cell.column.id}
							<Table.Cell
								class={[
									colId === 'select' &&
										'sticky left-0 z-30 min-w-[2.75rem] border-r border-border/70 shadow-[4px_0_12px_-6px_rgba(0,0,0,0.12)] dark:shadow-[4px_0_12px_-6px_rgba(0,0,0,0.35)]',
									colId === lastCellColId &&
										'sticky right-0 z-30 border-l border-border/70 shadow-[-4px_0_12px_-6px_rgba(0,0,0,0.12)] dark:shadow-[-4px_0_12px_-6px_rgba(0,0,0,0.35)]',
									row.getIsSelected()
										? 'bg-gray-300 dark:bg-gray-600'
										: 'bg-background group-hover/inv-list:bg-gray-100 dark:group-hover/inv-list:bg-gray-700'
								]
									.filter(Boolean)
									.join(' ')}
							>
								<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}

				<!-- Loading Trigger - Se activa cuando es visible -->
				{#if hasMore}
					<Table.Row>
						<Table.Cell colspan={columns.length} class="h-20 text-center">
							<div bind:this={loadingTrigger}>
								{#if loading}
									<div class="flex items-center justify-center gap-2">
										<div
											class="h-4 w-4 animate-spin rounded-full border-2 border-primary border-t-transparent"
										></div>
										<span class="text-sm text-muted-foreground">Cargando más...</span>
									</div>
								{:else}
									<div class="text-sm text-muted-foreground">Desplázate para cargar más</div>
								{/if}
							</div>
						</Table.Cell>
					</Table.Row>
				{/if}
			</Table.Body>
		</Table.Root>
	</div>
</div>
