<script lang="ts">
	import * as Dialog from '$lib/components/ui/dialog';
	import { Input } from '$lib/components/ui/input';
	import { Label } from '$lib/components/ui/label';
	import { Button } from '$lib/components/ui/button';
	import { Loader2, Search } from 'lucide-svelte';
	import {
		licenseExceptionsApi,
		type LicenseException
	} from '$lib/api/dashboard/reference_data/license_exceptions';
	import { onMount } from 'svelte';

	let {
		open = $bindable(false),
		onSelect,
		onClear
	}: { open: boolean; onSelect: (item: LicenseException) => void; onClear?: () => void } = $props();

	let items = $state<LicenseException[]>([]);
	let searchQ = $state('');
	let currentPage = $state(1);
	let totalItems = $state(0);
	let hasMore = $state(true);
	let isLoading = $state(false);
	let searchTimeout: ReturnType<typeof setTimeout>;

	let wasOpen = $state(false);

	$effect(() => {
		if (open && !wasOpen) {
			searchQ = '';
			currentPage = 1;
			items = [];
			loadItems('', 1);
		}
		wasOpen = open;
	});

	async function loadItems(search: string, page: number = currentPage) {
		if (isLoading) return;

		isLoading = true;
		try {
			const res = await licenseExceptionsApi.list(page, 50, search);

			if (res.data) {
				if (page === 1) {
					items = [...res.data.items];
				} else {
					items = [...items, ...res.data.items];
				}
				totalItems = res.data.total;
				currentPage = page;
				hasMore = items.length < res.data.total;
			}
		} catch (error) {
			console.error('Error cargando excepciones de licencia:', error);
		} finally {
			isLoading = false;
		}
	}
</script>

<Dialog.Root bind:open>
	<Dialog.Content class="z-[9999] w-full max-w-[95vw] sm:max-w-3xl">
		<Dialog.Header>
			<Dialog.Title>SELECCIONAR SÍMBOLO DE EXCEPCIÓN</Dialog.Title>
		</Dialog.Header>
		<div class="space-y-4">
			<div>
				<Label for="search_le">Buscar:</Label>
				<div class="relative mt-1">
					<Search class="absolute top-2.5 left-2 h-4 w-4 text-muted-foreground" />
					<Input
						id="search_le"
						bind:value={searchQ}
						placeholder="Clave o descripción..."
						class="pl-8"
						oninput={() => {
							clearTimeout(searchTimeout);
							searchTimeout = setTimeout(() => {
								items = [];
								currentPage = 1;
								loadItems(searchQ, 1);
							}, 400);
						}}
					/>
				</div>
			</div>
			<div
				class="max-h-[400px] overflow-auto rounded-md border"
				onscroll={(e) => {
					const target = e.currentTarget;
					if (
						target.scrollHeight - target.scrollTop <= target.clientHeight + 50 &&
						hasMore &&
						!isLoading
					) {
						loadItems(searchQ, currentPage + 1);
					}
				}}
			>
				<table class="w-full text-sm">
					<thead class="sticky top-0 z-10 border-b bg-background">
						<tr>
							<th class="w-24 px-4 py-2 text-left font-semibold">Clave</th>
							<th class="px-4 py-2 text-left font-semibold">Descripción</th>
						</tr>
					</thead>
					<tbody>
						{#each items as item (item.key)}
							<tr
								class="cursor-pointer border-b transition-colors hover:bg-muted/50"
								onclick={() => {
									onSelect(item);
									open = false;
								}}
							>
								<td class="px-4 py-2 font-mono font-bold text-primary">{item.key}</td>
								<td class="px-4 py-2">{item.description}</td>
							</tr>
						{:else}
							<tr>
								<td colspan="2" class="px-4 py-8 text-center text-muted-foreground">
									{#if isLoading}
										<div class="flex items-center justify-center gap-2">
											<Loader2 class="h-4 w-4 animate-spin" />
											Buscando...
										</div>
									{:else}
										No se encontraron registros
									{/if}
								</td>
							</tr>
						{/each}
					</tbody>
				</table>
			</div>
		</div>
		<div class="flex justify-end gap-2 pt-4">
			{#if onClear}
				<Button variant="ghost" class="mr-auto" onclick={() => { onClear(); open = false; }}>Quitar selección</Button>
			{/if}
			<Button variant="outline" onclick={() => (open = false)}>Cancelar</Button>
		</div>
	</Dialog.Content>
</Dialog.Root>
