<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 { Search, Loader2 } from 'lucide-svelte';
	import { invoicesApi, type Invoice } from '$lib/api/dashboard/a76/invoices';
	import { companyStore } from '$lib/stores/company.svelte';
	import { toast } from 'svelte-sonner';

	let {
		open = $bindable(false),
		regimen = 'Temporal',
		onSelect
	}: {
		open: boolean;
		regimen: string;
		onSelect: (invoice: Invoice) => void;
	} = $props();

	let invoices = $state<Invoice[]>([]);
	let loading = $state(false);
	let searchTerm = $state('');

	async function searchInvoices() {
		if (!companyStore.activeCompany) return;
		loading = true;
		try {
			let filters: any = {
				operation_type: 'imp',
				invoice_number: searchTerm
			};

			if (regimen === 'Temporal' || regimen === 'TEMPORAL SCAF') {
				filters.invoice_type = 'TEM';
			} else if (regimen === 'Definitiva' || regimen === 'DEFINITIVO SCAF') {
				filters.invoice_type = 'DEF';
			}

			const res = await invoicesApi.list(companyStore.activeCompany.id, 1, 50, filters);
			if (res.data) {
				invoices = res.data.items || [];
			}
		} catch (e) {
			console.error('Error searching invoices:', e);
			toast.error('Error al buscar facturas');
		} finally {
			loading = false;
		}
	}

	function handleSelect(invoice: Invoice) {
		onSelect(invoice);
		open = false;
	}

	$effect(() => {
		if (open) {
			searchInvoices();
		}
	});
</script>

<Dialog.Root bind:open>
	<Dialog.Content class="max-w-2xl">
		<Dialog.Header>
			<Dialog.Title>Seleccionar Factura ({regimen})</Dialog.Title>
			<Dialog.Description>
				Busca y selecciona una factura del catálogo de importación para el régimen {regimen}.
			</Dialog.Description>
		</Dialog.Header>

		<div class="space-y-4 py-4">
			<div class="flex gap-2">
				<div class="relative flex-1">
					<Search class="absolute top-2.5 left-2.5 h-4 w-4 text-muted-foreground" />
					<Input
						placeholder="Buscar por número..."
						class="h-9 pl-8"
						bind:value={searchTerm}
						onkeydown={(e) => e.key === 'Enter' && searchInvoices()}
					/>
				</div>
				<Button size="sm" onclick={searchInvoices} disabled={loading}>
					{#if loading}
						<Loader2 class="mr-2 h-4 w-4 animate-spin" />
					{/if}
					Buscar
				</Button>
			</div>

			<div class="max-h-[400px] overflow-y-auto rounded-md border text-xs">
				<table class="w-full">
					<thead class="sticky top-0 bg-muted/90 text-left backdrop-blur-sm">
						<tr>
							<th class="p-3 font-semibold tracking-wider text-muted-foreground uppercase"
								>Número de Factura</th
							>
							<th class="p-3 font-semibold tracking-wider text-muted-foreground uppercase"
								>Pedimento</th
							>
						</tr>
					</thead>
					<tbody class="divide-y">
						{#if invoices.length === 0}
							<tr>
								<td colspan="2" class="p-12 text-center text-muted-foreground">
									{#if loading}
										Buscando facturas...
									{:else}
										No se encontraron resultados
									{/if}
								</td>
							</tr>
						{:else}
							{#each invoices as invoice}
								<tr
									class="group cursor-pointer transition-colors hover:bg-muted/50"
									onclick={() => handleSelect(invoice)}
								>
									<td
										class="p-3 font-mono font-bold text-primary transition-colors group-hover:text-primary/80"
									>
										{invoice.invoice_number}
									</td>
									<td class="max-w-[400px] truncate p-3 text-muted-foreground italic">
										{invoice.compliance_mx?.pedimento_r1 ||
											invoice.compliance_mx?.pedimento_id ||
											'-'}
									</td>
								</tr>
							{/each}
						{/if}
					</tbody>
				</table>
			</div>
		</div>
	</Dialog.Content>
</Dialog.Root>
