<script lang="ts" generics="TData, TValue">
	import { onMount } from 'svelte';
	import {
		type ColumnDef,
		getCoreRowModel,
		type RowSelectionState
	} 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";
	import { Button } from "$lib/components/ui/button";
	import { Edit } from "lucide-svelte";

	type DataTableProps<TData, TValue> = {
		columns: ColumnDef<TData, TValue>[];
		data: TData[];
		loading: boolean;
		hasMore: boolean;
		loadMore: () => void;
		selectedId?: number | null;
		onRowClick?: (row: TData) => void;
	};

	let {
		data,
		columns,
		loading,
		hasMore,
		loadMore,
		selectedId = null,
		onRowClick
	}: DataTableProps<TData, TValue> = $props();

	const table = createSvelteTable({
		get data() {
			return data;
		},
		columns,
		getCoreRowModel: getCoreRowModel(),
		getRowId: (row: any) => row.id?.toString(),
		state: {
			get rowSelection() {
				return selectedId ? { [selectedId]: true } : {};
			}
		},
		enableRowSelection: true,
		enableMultiRowSelection: false
	});

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

	// Función para manejar doble clic en una fila
	function handleRowDoubleClick(row: any) {
		const pedimento = row.original;
		if (pedimento?.id) {
			window.location.href = `/dashboard/pedimentos/edit/${pedimento.id}`;
		}
	}

	// 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="rounded-md border max-h-[600px] overflow-auto" bind:this={scrollContainer}>
		<Table.Root class="w-full">
			<Table.Header class="bg-background sticky top-0 z-10">
				{#each table.getHeaderGroups() as headerGroup (headerGroup.id)}
					<Table.Row>
						{#each headerGroup.headers as header (header.id)}
							<Table.Head class="whitespace-nowrap {header.column.columnDef.meta?.className || ''}">
								{#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 
						data-state={row.getIsSelected() && "selected"}
						onclick={() => {
							if (onRowClick) {
								onRowClick(row.original);
							}
						}}
						ondblclick={() => handleRowDoubleClick(row)}
						class="cursor-pointer hover:bg-muted/50 transition-colors {row.getIsSelected() ? 'bg-primary/10' : ''}"
					>
						{#each row.getVisibleCells() as cell (cell.id)}
							<Table.Cell class="whitespace-nowrap {cell.column.columnDef.meta?.className || ''}">
								<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-muted-foreground text-sm">Cargando más...</span>
									</div>
								{:else}
									<div class="text-muted-foreground text-sm">
										Desplázate para cargar más
									</div>
								{/if}
							</div>
						</Table.Cell>
					</Table.Row>
				{/if}
			</Table.Body>
		</Table.Root>
	</div>
</div>
