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

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

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

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

	function filterMethods() {
		if (!searchTerm.trim()) {
			filteredMethods = paymentMethods;
		} else {
			const term = searchTerm.toLowerCase();
			filteredMethods = paymentMethods.filter(
				(method) =>
					method.key?.toLowerCase().includes(term) ||
					method.description?.toLowerCase().includes(term)
			);
		}
	}

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

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

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

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

<Dialog.Root bind:open>
	<Dialog.Content class="!max-w-[60vw] w-[60vw] 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 FORMAS DE PAGO</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"
									>Descripción</th
								>
							</tr>
						</thead>
						<tbody>
							{#each filteredMethods as method, i}
								<tr
									class="border-b hover:bg-zinc-100 dark:hover:bg-zinc-800 cursor-pointer transition-colors"
									tabindex="0"
									onclick={() => handleSelect(method)}
									onkeydown={(event) => handleRowKeydown(event, method)}
								>
									<td class="px-3 py-2 border-r text-center">{method.key || ''}</td>
									<td class="px-3 py-2">{method.description || ''}</td>
								</tr>
							{/each}
							{#if filteredMethods.length === 0}
								<tr>
									<td colspan="2" 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">
			{#if onClear}
				<Button variant="ghost" onclick={() => { onClear(); open = false; }}>Quitar selección</Button>
			{/if}
			<Button variant="outline" onclick={() => (open = false)}>
				Cancelar
			</Button>
		</div>
	</Dialog.Content>
</Dialog.Root>
