<script lang="ts">
	import { Input } from '$lib/components/ui/input';
	import { Button } from '$lib/components/ui/button';
	import * as Table from '$lib/components/ui/table';
	import * as Card from '$lib/components/ui/card';
	import { onMount, untrack } from 'svelte';
	import { toast } from 'svelte-sonner';
	import { getSectors, type Sector } from '$lib/api/dashboard/general_catalogs/sectors';
	import { Loader2, Search } from 'lucide-svelte';
	import Badge from '$lib/components/ui/badge/badge.svelte';

	let { title = 'Sectores' }: { title?: string } = $props();

	let sectors = $state<Sector[]>([]);
	let loading = $state(false);
	let searchTerm = $state('');
	let page = $state(1);
	let pageSize = 50;
	let hasMore = $state(true);
	let total = $state(0);
	let searchTimeout: ReturnType<typeof setTimeout>;
	let observer: IntersectionObserver;
	let sentinel: HTMLDivElement;

	async function loadSectors(reset = false) {
		if (loading || (!hasMore && !reset)) return;
		loading = true;

		if (reset) {
			page = 1;
			sectors = [];
			hasMore = true;
		} else {
			page++;
		}

		try {
			const response = await getSectors(page, pageSize, searchTerm || undefined);

			const newItems = response.items || [];
			if (reset) {
				sectors = newItems;
			} else {
				sectors = [...sectors, ...newItems];
			}

			total = response.total;
			// Safer end-of-data detection
			hasMore = newItems.length === pageSize && sectors.length < total;
		} catch (error) {
			console.error('Error loading sectors:', error);
			toast.error('Error al cargar sectores');
			hasMore = false;
		} finally {
			loading = false;
		}
	}

	function handleSearch() {
		loadSectors(true);
	}

	function handleSearchInput() {
		clearTimeout(searchTimeout);
		searchTimeout = setTimeout(() => {
			loadSectors(true);
		}, 500);
	}

	function handleKeyDown(event: KeyboardEvent) {
		if (event.key === 'Enter') {
			clearTimeout(searchTimeout);
			handleSearch();
		}
	}

	function setupObserver() {
		if (observer) observer.disconnect();

		observer = new IntersectionObserver(
			(entries) => {
				if (entries[0].isIntersecting && hasMore && !loading && sectors.length > 0) {
					loadSectors(false);
				}
			},
			{ rootMargin: '100px' }
		);

		if (sentinel) observer.observe(sentinel);
	}

	// Initial load
	$effect(() => {
		untrack(() => loadSectors(true));
	});

	// Setup observer only when sentinel is available
	$effect(() => {
		if (sentinel) {
			setupObserver();
			return () => observer?.disconnect();
		}
	});
</script>

<div class="space-y-4">
	<div class="flex items-center justify-between">
		<h2 class="text-3xl font-bold tracking-tight">{title}</h2>
	</div>

	<Card.Root>
		<Card.Header>
			<div class="flex w-full items-center gap-4">
				<div class="relative flex-1">
					<Search class="absolute top-2.5 left-2.5 h-4 w-4 text-muted-foreground" />
					<Input
						placeholder="Buscar por clave o descripción..."
						class="pl-8"
						bind:value={searchTerm}
						oninput={handleSearchInput}
						onkeydown={handleKeyDown}
					/>
				</div>
			</div>
		</Card.Header>
		<Card.Content>
			<div class="rounded-md border">
				<Table.Root>
					<Table.Header>
						<Table.Row>
							<Table.Head class="w-[100px]">Clave</Table.Head>
							<Table.Head>Descripción</Table.Head>
							<Table.Head class="text-right">Estatus</Table.Head>
						</Table.Row>
					</Table.Header>
					<Table.Body>
						{#if loading && page === 1}
							<Table.Row>
								<Table.Cell colspan={3} class="h-24 text-center">
									<div class="flex justify-center">
										<Loader2 class="h-6 w-6 animate-spin" />
									</div>
								</Table.Cell>
							</Table.Row>
						{:else if sectors.length === 0}
							<Table.Row>
								<Table.Cell colspan={3} class="h-24 text-center">
									No se encontraron sectores.
								</Table.Cell>
							</Table.Row>
						{:else}
							{#each sectors as sector}
								<Table.Row>
									<Table.Cell class="font-medium">{sector.key}</Table.Cell>
									<Table.Cell>{sector.description}</Table.Cell>
									<Table.Cell class="text-right">
										{#if sector.authorized}
											<Badge variant="default">Autorizado</Badge>
										{:else}
											<Badge variant="secondary">No Autorizado</Badge>
										{/if}
									</Table.Cell>
								</Table.Row>
							{/each}
						{/if}
						{#if loading && page > 1}
							<Table.Row>
								<Table.Cell colspan={3} class="h-12 text-center">
									<div class="flex justify-center">
										<Loader2 class="h-4 w-4 animate-spin" />
									</div>
								</Table.Cell>
							</Table.Row>
						{/if}
					</Table.Body>
				</Table.Root>
			</div>

			<div class="mt-4 flex flex-col items-center gap-2">
				<div class="text-xs text-muted-foreground">
					Mostrando {sectors.length} de {total} registros
				</div>
				<!-- Infinite Scroll Sentinel -->
				<div bind:this={sentinel} class="h-4 w-full"></div>
			</div>
		</Card.Content>
	</Card.Root>
</div>
