<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';

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

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

	async function loadCountries() {
		loading = true;
		error = '';
		try {
			const response = await fetch('/api-sveltekit/countries', {
				credentials: 'include'
			});
			if (response.ok) {
				const data = await response.json();				
				if (Array.isArray(data)) {
					countries = data;
				} else if (data.items && Array.isArray(data.items)) {
					countries = data.items;
				} else {
					console.error('Unexpected data format:', data);
					countries = [];
				}
				filteredCountries = countries;				
			} else {
				error = `Error: ${response.status} - ${response.statusText}`;
				console.error('Error response:', await response.text());
			}
		} catch (err) {
			error = 'Error loading countries';
			console.error('Error loading countries:', err);
		} finally {
			loading = false;
		}
	}

	function filterCountries() {
		if (!searchTerm.trim()) {
			filteredCountries = countries;
		} else {
			const term = searchTerm.toLowerCase();
			filteredCountries = countries.filter(
				(country) =>
					country.m3_key?.toLowerCase().includes(term) ||
					country.mex_key?.toLowerCase().includes(term) ||
					country.description_es?.toLowerCase().includes(term) ||
					country.description_en?.toLowerCase().includes(term)
			);
		}
	}

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

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

	$effect(() => {
		filterCountries();
	});
</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 PAISES</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 M3</th
								>
								<th class="px-3 py-2 text-left font-semibold border-r border-zinc-700"
									>Clave Mexicana</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"
									>Clave Americana</th
								>
								<th class="px-3 py-2 text-left font-semibold">Descripción Inglés</th>
							</tr>
						</thead>
						<tbody>
							{#each filteredCountries as country, i}
								<tr
									class="border-b hover:bg-zinc-100 dark:hover:bg-zinc-800 cursor-pointer transition-colors"
									onclick={() => handleSelect(country)}
								>
								<td class="px-3 py-2 border-r">{country.m3_key || ''}</td>
								<td class="px-3 py-2 border-r">{country.mex_key || ''}</td>
								<td class="px-3 py-2 border-r">{country.description_es || ''}</td>
								<td class="px-3 py-2 border-r text-center">{country.ame_key || ''}</td>
								<td class="px-3 py-2">{country.description_en || ''}</td>
								</tr>
							{/each}
							{#if filteredCountries.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>

				<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">
			<Button variant="outline" size="sm">Editar</Button>
		</div>
	</Dialog.Content>
</Dialog.Root>
