<script lang="ts">
	import { Button } from '$lib/components/ui/button';
	import { Input } from '$lib/components/ui/input';
	import * as Dialog from '$lib/components/ui/dialog';
	import { Search, Loader2, MapPin } from 'lucide-svelte';
	import { toast } from 'svelte-sonner';
	import {
		customsSectionsApi,
		type CustomsSection
	} from '$lib/api/dashboard/reference_data/customs_sections';

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

	let items = $state<CustomsSection[]>([]);
	let loading = $state(false);
	let searchTerm = $state('');
	let loaded = $state(false);

	let filteredItems = $derived(
		items.filter((i) => {
			const search = searchTerm.toLowerCase();
			return (
				!searchTerm ||
				(i.section_name?.toLowerCase() || '').includes(search) ||
				(i.customs_code?.toLowerCase() || '').includes(search)
			);
		})
	);

	$effect(() => {
		if (open && !loaded) {
			loadItems();
		}
	});

	async function loadItems() {
		loading = true;
		try {
			// Customs sections are public reference data
			// Reduced page_size to 100 to comply with backend constraints (le=100)
			const res = await customsSectionsApi.list(1, 100);
			const data = (res.data || res) as any;
			if (data) {
				// Handle both direct array and object-with-items wrapper
				items = Array.isArray(data) ? data : data.items || [];
				loaded = true;
			} else if (res.error) {
				console.error('API Error loading customs sections:', res.error);
				toast.error('Error al cargar secciones: ' + res.error);
			}
		} catch (e) {
			console.error('Error loading customs sections:', e);
			toast.error('Error de conexión al cargar las secciones');
			// Even on error, mark as loaded to prevent infinite loops, or handle with a retry button
			loaded = true;
		} finally {
			loading = false;
		}
	}

	function handleSelect(item: CustomsSection) {
		if (onSelect) onSelect(item);
		open = false;
	}

	function handleRowKeydown(event: KeyboardEvent, item: CustomsSection) {
		if (event.key === 'Enter' || event.key === ' ') {
			event.preventDefault();
			handleSelect(item);
		}
	}
</script>

<Dialog.Root bind:open>
	<Dialog.Content class="flex max-h-[80vh] flex-col sm:max-w-[700px]">
		<Dialog.Header>
			<Dialog.Title>Seleccionar Sección Aduanera</Dialog.Title>
			<Dialog.Description>Catálogo general de aduanas y secciones.</Dialog.Description>
		</Dialog.Header>

		<div class="relative my-2 w-full">
			<Search class="absolute top-2.5 left-2.5 h-4 w-4 text-muted-foreground" />
			<Input
				type="search"
				placeholder="Buscar por descripción o código..."
				class="pl-9"
				bind:value={searchTerm}
			/>
		</div>

		<div class="min-h-[300px] flex-1 overflow-y-auto rounded-md border">
			{#if loading}
				<div class="flex h-48 flex-col items-center justify-center gap-2 text-muted-foreground">
					<Loader2 class="h-8 w-8 animate-spin text-primary" />
					<p>Cargando catálogo...</p>
				</div>
			{:else if filteredItems.length === 0}
				<div class="flex h-48 flex-col items-center justify-center text-muted-foreground">
					<p>No se encontraron registros.</p>
				</div>
			{:else}
				<table class="w-full text-sm">
					<thead class="bg-muted/50">
						<tr class="border-b text-left">
							<th class="w-[100px] p-3 font-medium text-muted-foreground">Código</th>
							<th class="p-3 font-medium text-muted-foreground">Descripción</th>
						</tr>
					</thead>
					<tbody>
						{#each filteredItems as item}
							<tr
								class="cursor-pointer border-b transition-colors hover:bg-accent/50"
								tabindex="0"
								onclick={() => handleSelect(item)}
								onkeydown={(event) => handleRowKeydown(event, item)}
							>
								<td class="p-3 font-mono font-bold text-primary">{item.customs_code}</td>
								<td class="p-3">
									<div class="flex items-center gap-2">
										<MapPin class="h-3 w-3 text-muted-foreground" />
										{item.section_name || '-'}
									</div>
								</td>
							</tr>
						{/each}
					</tbody>
				</table>
			{/if}
		</div>

		<Dialog.Footer>
			<div class="mr-auto self-center text-xs text-muted-foreground">
				Mostrando {filteredItems.length} registros
			</div>
			{#if onClear}
				<Button variant="ghost" onclick={() => { onClear(); open = false; }}>Quitar selección</Button>
			{/if}
			<Button variant="outline" onclick={() => (open = false)}>Cancelar</Button>
		</Dialog.Footer>
	</Dialog.Content>
</Dialog.Root>
