<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';
	import { m } from '$lib/i18n/messages';

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

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

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

	function filterUnits() {
		if (!searchTerm.trim()) {
			filteredUnits = units;
		} else {
			const term = searchTerm.toLowerCase();
			filteredUnits = units.filter(
				(unit) =>
					unit.code?.toLowerCase().includes(term) ||
					unit.description?.toLowerCase().includes(term) ||
					unit.description_en?.toLowerCase().includes(term)
			);
		}
	}

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

	function handleRowKeydown(event: KeyboardEvent, unit: any) {
		if (event.key === 'Enter' || event.key === ' ') {
			event.preventDefault();
			handleSelect(unit);
		}
	}

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

	$effect(() => {
		filterUnits();
	});
</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">CATALOGOS DE UNIDADES DE MEDIDA</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"
									>U.M.</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"
									>Abrév. Inglés</th
								>
								<th class="px-3 py-2 text-left font-semibold border-r border-zinc-700"
									>Clave Aduana</th
								>
								<th class="px-3 py-2 text-left font-semibold border-r border-zinc-700"
									>Clave Americana</th
								>
								<th class="px-3 py-2 text-left font-semibold">Clave O.M.A.</th>
							</tr>
						</thead>
						<tbody>
							{#each filteredUnits as unit, i}
								<tr
									class="border-b hover:bg-zinc-100 dark:hover:bg-zinc-800 cursor-pointer transition-colors"
									tabindex="0"
									onclick={() => handleSelect(unit)}
									onkeydown={(event) => handleRowKeydown(event, unit)}
								>
									<td class="px-3 py-2 border-r">{unit.code || ''}</td>
									<td class="px-3 py-2 border-r">{unit.description || ''}</td>
									<td class="px-3 py-2 border-r">{unit.description_en || ''}</td>
									<td class="px-3 py-2 border-r text-center">{unit.customs_code || ''}</td>
									<td class="px-3 py-2 border-r text-center">{unit.american_code || ''}</td>
									<td class="px-3 py-2 text-center">{unit.oma_code || ''}</td>
								</tr>
							{/each}
							{#if filteredUnits.length === 0}
								<tr>
									<td colspan="6" class="px-3 py-8 text-center text-zinc-500">
										No se encontraron resultados
									</td>
								</tr>
							{/if}
						</tbody>
					</table>
				</div>

				<div class="mt-4 flex items-center justify-between text-sm text-zinc-600 dark:text-zinc-400">
					<div class="flex items-center gap-4">
						<button class="px-3 py-1 border rounded hover:bg-zinc-100 dark:hover:bg-zinc-800">
							&lt;&lt;
						</button>
						<button class="px-3 py-1 border rounded hover:bg-zinc-100 dark:hover:bg-zinc-800">
							&lt;
						</button>
						<button class="px-3 py-1 border rounded hover:bg-zinc-100 dark:hover:bg-zinc-800">
							&gt;
						</button>
						<button class="px-3 py-1 border rounded hover:bg-zinc-100 dark:hover:bg-zinc-800">
							&gt;&gt;
						</button>
					</div>
				</div>
			{/if}
		</div>

		<div class="px-6 py-3 border-t bg-zinc-50 dark:bg-zinc-900 flex items-center justify-end gap-2">
			{#if onClear}
				<Button variant="ghost" size="sm" onclick={() => { onClear(); open = false; }}>Quitar selección</Button>
			{/if}
			<Button variant="outline" size="sm">Editar</Button>
		</div>
	</Dialog.Content>
</Dialog.Root>
