<script lang="ts">
	import * as Dialog from '$lib/components/ui/dialog';
	import { Button } from '$lib/components/ui/button';
	import { Input } from '$lib/components/ui/input';
	import { Loader2, Search } from 'lucide-svelte';
	import { onMount } from 'svelte';

	let {
		open = $bindable(),
		onSelect
	}: {
		open: boolean;
		onSelect: (pkg: any) => void;
	} = $props();

	let packages: any[] = $state([]);
	let filteredPackages: any[] = $state([]);
	let loading = $state(false);
	let searchTerm = $state('');
	let error = $state('');

	async function loadPackages() {
		loading = true;
		error = '';
		try {
			const response = await fetch('/api-sveltekit/packages', {
				credentials: 'include'
			});
			if (response.ok) {
				const data = await response.json();				
				// El backend puede devolver { items: [...] } o directamente un array
				if (Array.isArray(data)) {
					packages = data;
				} else if (data.items && Array.isArray(data.items)) {
					packages = data.items;
				} else if (data.data && Array.isArray(data.data)) {
					packages = data.data;
				} else {
					console.error('Unexpected data format:', data);
					packages = [];
				}
				filteredPackages = packages;
			} else {
				error = `Error: ${response.status} - ${response.statusText}`;
				console.error('Error response:', await response.text());
			}
		} catch (err) {
			error = 'Error loading packages';
			console.error('Error loading packages:', err);
		} finally {
			loading = false;
		}
	}

	function filterPackages() {
		if (!searchTerm.trim()) {
			filteredPackages = packages;
		} else {
			const term = searchTerm.toLowerCase();
			filteredPackages = packages.filter(
				(pkg) =>
					pkg.key?.toLowerCase().includes(term) ||
					pkg.description_es?.toLowerCase().includes(term) ||
					pkg.description_en?.toLowerCase().includes(term)
			);
		}
	}

	function handleSelect(pkg: any) {
		onSelect(pkg);
		open = false;
	}

	$effect(() => {
		if (open) {
			loadPackages();
		}
	});

	$effect(() => {
		filterPackages();
	});
</script>

<Dialog.Root bind:open>
	<Dialog.Content class="!max-w-[70vw] w-[70vw] max-h-[90vh] p-0 flex flex-col">
		<Dialog.Header class="px-6 py-4 border-b">
			<Dialog.Title class="text-lg font-semibold">CATALOGO DE BULTOS</Dialog.Title>
		</Dialog.Header>

		<div class="px-6 py-3 border-b bg-zinc-50 dark:bg-zinc-900">
			<div class="flex items-center gap-2">
				<Search class="w-4 h-4 text-zinc-400" />
				<Input
					bind:value={searchTerm}
					placeholder="Buscando..."
					class="flex-1 h-9"
				/>
			</div>
		</div>

		<div class="flex-1 overflow-auto px-6 py-4">
			{#if loading}
				<div class="flex items-center justify-center py-20">
					<Loader2 class="w-8 h-8 animate-spin text-zinc-900 dark:text-zinc-100" />
				</div>
			{:else if error}
				<div class="flex items-center justify-center py-20 text-red-600">
					<p>{error}</p>
				</div>
			{:else}
				<div class="border rounded-md overflow-hidden">
					<table class="w-full text-sm">
						<thead class="bg-zinc-900 dark:bg-zinc-800 text-white">
							<tr>
								<th class="px-3 py-2 text-left font-semibold border-r border-zinc-700"
									>Clave</th
								>
								<th class="px-3 py-2 text-left font-semibold border-r border-zinc-700"
									>Descripción Español</th
								>
								<th class="px-3 py-2 text-left font-semibold border-r border-zinc-700"
									>Descripción Inglés</th
								>
								<th class="px-3 py-2 text-left font-semibold border-r border-zinc-700"
									>Peso Unitario</th
								>
								<th class="px-3 py-2 text-left font-semibold">Código ACE</th>
							</tr>
						</thead>
						<tbody>
							{#each filteredPackages as pkg, i}
								<tr
									class="border-b hover:bg-zinc-100 dark:hover:bg-zinc-800 cursor-pointer transition-colors"
									onclick={() => handleSelect(pkg)}
								>
									<td class="px-3 py-2 border-r">{pkg.key || ''}</td>
									<td class="px-3 py-2 border-r">{pkg.description_es || ''}</td>
									<td class="px-3 py-2 border-r">{pkg.description_en || ''}</td>
									<td class="px-3 py-2 border-r text-right">{pkg.weight_unit || ''}</td>
									<td class="px-3 py-2 text-center">{pkg.code_ace || ''}</td>
								</tr>
							{/each}
							{#if filteredPackages.length === 0}
								<tr>
									<td colspan="5" class="px-3 py-8 text-center text-zinc-500">
										No se encontraron resultados
									</td>
								</tr>
							{/if}
						</tbody>
					</table>
				</div>
			{/if}
		</div>

		<div class="px-6 py-4 border-t flex justify-end gap-2">
			<Button variant="outline" onclick={() => (open = false)}>
				Cancelar
			</Button>
		</div>
	</Dialog.Content>
</Dialog.Root>
