<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, AlertCircle } from 'lucide-svelte';
	import { cartaPorteApi, type CartaPorte } from '$lib/api/dashboard/reference_data/carta_porte';

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

	let items = $state<CartaPorte[]>([]);
	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 = [];
			// Solo cargar si hay búsqueda o si el usuario lo solicita para no saturar 30k registros
			loadItems('', 1);
		}
		wasOpen = open;
	});

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

		isLoading = true;
		try {
			const res = await cartaPorteApi.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 carta porte:', error);
		} finally {
			isLoading = false;
		}
	}
</script>

<Dialog.Root bind:open>
	<Dialog.Content class="z-[9999] w-full max-w-[95vw] sm:max-w-6xl">
		<Dialog.Header>
			<Dialog.Title class="flex items-center gap-2">
				CATÁLOGO CARTA PORTE (30,000+ REGISTROS)
				{#if totalItems > 0}
					<span class="text-xs font-normal text-muted-foreground">(Total: {totalItems})</span>
				{/if}
			</Dialog.Title>
		</Dialog.Header>
		
		<div class="space-y-4">
			<div class="bg-primary/5 p-3 rounded-lg border border-primary/20 flex items-center gap-3">
				<AlertCircle class="h-5 w-5 text-primary" />
				<p class="text-[10px] leading-tight text-primary-foreground/80">
					Este catálogo es muy extenso. Use el buscador para encontrar códigos por <strong>descripción</strong> o <strong>código SAT</strong> de forma precisa.
				</p>
			</div>

			<div>
				<Label for="search_cp">Buscador Inteligente:</Label>
				<div class="relative mt-1">
					<Search class="absolute top-2.5 left-2 h-4 w-4 text-muted-foreground" />
					<Input
						id="search_cp"
						bind:value={searchQ}
						placeholder="Escriba aquí para buscar..."
						class="pl-8 h-12 text-lg shadow-sm"
						oninput={() => {
							clearTimeout(searchTimeout);
							searchTimeout = setTimeout(() => {
								items = [];
								currentPage = 1;
								loadItems(searchQ, 1);
							}, 500);
						}}
					/>
				</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="px-3 py-2 text-left font-semibold w-16">ID</th>
							<th class="px-3 py-2 text-left font-semibold w-24">Código SAT</th>
							<th class="px-3 py-2 text-left font-semibold">Descripción Mercancía / Similares</th>
							<th class="px-3 py-2 text-center font-semibold w-24">Mat. Peligroso</th>
							<th class="px-3 py-2 text-left font-semibold w-24">Inicio Vigencia</th>
							<th class="px-3 py-2 text-left font-semibold w-24">Fin Vigencia</th>
						</tr>
					</thead>
					<tbody>
						{#each items as item (item.id)}
							<tr
								class="cursor-pointer border-b transition-colors hover:bg-muted/50"
								onclick={() => {
									onSelect(item);
									open = false;
								}}
							>
								<td class="px-3 py-3 font-mono text-muted-foreground">{item.id}</td>
								<td class="px-3 py-3 font-mono font-bold group-hover:text-primary">{item.code}</td>
								<td class="px-3 py-3">
									<div class="font-medium">{item.description}</div>
									{#if item.similar_words}
										<div class="text-[10px] text-muted-foreground mt-1 line-clamp-2" title={item.similar_words}>Similares: {item.similar_words}</div>
									{/if}
								</td>
								<td class="px-3 py-3 text-center">
									{#if item.is_hazardous}
										<span class="px-1.5 py-0.5 rounded bg-amber-100 text-amber-700 text-[10px] font-bold border border-amber-200">SÍ</span>
									{:else}
										<span class="text-muted-foreground text-[10px]">No</span>
									{/if}
								</td>
								<td class="px-3 py-3 text-xs opacity-80">{item.start_date || '-'}</td>
								<td class="px-3 py-3 text-xs opacity-80">{item.end_date || '-'}</td>
							</tr>
						{:else}
							<tr>
								<td colspan="6" class="px-4 py-8 text-center text-muted-foreground">
									{#if isLoading}
										<div class="flex flex-col items-center justify-center gap-3">
											<Loader2 class="h-8 w-8 animate-spin text-primary" />
											<span class="text-sm">Buscando en más de 30k registros...</span>
										</div>
									{:else}
										No se han encontrado resultados. Intente con otra palabra.
									{/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)}>Cerrar</Button>
		</div>
	</Dialog.Content>
</Dialog.Root>
