<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;
		sorting?: import("@tanstack/table-core").SortingState;
		onSortingChange?: (sorting: import("@tanstack/table-core").SortingState) => void;
	};

	let {
		data,
		columns,
		loading,
		hasMore,
		loadMore,
		selectedId = null,
		onRowClick,
		sorting = [],
		onSortingChange
	}: 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 } : {};
			},
			get sorting() {
				return sorting;
			}
		},
		onSortingChange: (updater) => {
			if (onSortingChange) {
				const nextSorting = typeof updater === 'function' ? updater(sorting) : updater;
				onSortingChange(nextSorting);
			}
		},
		manualSorting: 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
	$effect(() => {
		const target = loadingTrigger;
		const root = scrollContainer;
		if (!target) return;

		const observer = new IntersectionObserver(
			(entries) => {
				const [entry] = entries;
				if (entry.isIntersecting && hasMore && !loading) {
					loadMore();
				}
			},
			{
				root: root,
				threshold: 0.1
			}
		);

		observer.observe(target);

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

<div class="w-full" data-pedimento-list-table>
	<div
		class="min-h-[360px] max-h-[calc(100svh-420px)] overflow-auto rounded-md border bg-background [&_[data-slot=table-container]]:overflow-visible [&_[data-slot=table-container]]:w-full"
		bind:this={scrollContainer}
	>
		<div class="min-w-max">
			<Table.Root>
			<Table.Header class="sticky top-0 z-20 border-b bg-background/95 shadow-sm backdrop-blur-md">
				{#each table.getHeaderGroups() as headerGroup (headerGroup.id)}
						<Table.Row inTabOrder={false}>
						{#each headerGroup.headers as header (header.id)}
								{@const colId = header.column.id}
								<Table.Head
								class="whitespace-nowrap text-sm font-semibold text-foreground/90 p-0 {header.column.columnDef.meta?.className || ''} {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)]'
										: ''}"
								>
								{#if !header.isPlaceholder}
									<button
										class="group flex h-full w-full items-center justify-between gap-2 px-2 py-2 text-left {header.column.getCanSort() ? 'cursor-pointer select-none' : ''}"
										onclick={header.column.getToggleSortingHandler()}
										disabled={!header.column.getCanSort()}
									>
										<FlexRender
											content={header.column.columnDef.header}
											context={header.getContext()}
										/>
										{#if header.column.getCanSort()}
											<div class="flex h-4 w-4 shrink-0 items-center justify-center">
												{#if header.column.getIsSorted() === 'asc'}
													<svg
														xmlns="http://www.w3.org/2000/svg"
														width="14"
														height="14"
														viewBox="0 0 24 24"
														fill="none"
														stroke="currentColor"
														stroke-width="2"
														stroke-linecap="round"
														stroke-linejoin="round"
														class="lucide lucide-chevron-up text-primary"
														><path d="m18 15-6-6-6 6" /></svg
													>
												{:else if header.column.getIsSorted() === 'desc'}
													<svg
														xmlns="http://www.w3.org/2000/svg"
														width="14"
														height="14"
														viewBox="0 0 24 24"
														fill="none"
														stroke="currentColor"
														stroke-width="2"
														stroke-linecap="round"
														stroke-linejoin="round"
														class="lucide lucide-chevron-down text-primary"
														><path d="m6 9 6 6 6-6" /></svg
													>
												{:else}
													<svg
														xmlns="http://www.w3.org/2000/svg"
														width="14"
														height="14"
														viewBox="0 0 24 24"
														fill="none"
														stroke="currentColor"
														stroke-width="2"
														stroke-linecap="round"
														stroke-linejoin="round"
														class="lucide lucide-chevrons-up-down opacity-30 group-hover:opacity-100"
														><path d="m7 15 5 5 5-5" /><path d="m7 9 5-5 5 5" /></svg
													>
												{/if}
											</div>
										{/if}
									</button>
								{/if}
							</Table.Head>
						{/each}
					</Table.Row>
				{/each}
			</Table.Header>
			<Table.Body>
				{#each table.getRowModel().rows as row (row.id)}
					<Table.Row 
						data-pedimento-data-row
						data-state={row.getIsSelected() && "selected"}
						onclick={() => {
							if (onRowClick) {
								onRowClick(row.original);
							}
						}}
						ondblclick={() => handleRowDoubleClick(row)}
						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'}"
					>
						{#each row.getVisibleCells() as cell (cell.id)}
									{@const colId = cell.column.id}
									<Table.Cell
										class="whitespace-nowrap {cell.column.columnDef.meta?.className || ''} {colId === 'select'
											? 'sticky left-0 z-30 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)]'
											: ''} {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'}"
									>
								<FlexRender
									content={cell.column.columnDef.cell}
									context={cell.getContext()}
								/>
							</Table.Cell>
						{/each}
					</Table.Row>
				{:else}
					<Table.Row inTabOrder={false}>
						<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 inTabOrder={false}>
						<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>
</div>
