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

	interface Props {
		open: boolean;
		regimen?: string;
		operationType?: 'imp' | 'exp';
		status?: string;
		onSelect: (invoice: Invoice) => void;
		onClear?: () => void;
	}

	let {
		open = $bindable(false),
		regimen = 'Temporal',
		operationType = 'imp' as 'imp' | 'exp',
		onSelect,
		onClear
	}: Props = $props();

	let status = $derived(operationType === 'imp' ? 'processed' : undefined);

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

	async function searchInvoices() {
		const activeCompanyId = companyStore?.activeCompany?.id;
		if (!activeCompanyId) {
			toast.error(m.invoice_selectors_invoice_selector_modal_no_active_company());
			return;
		}
		
		loading = true;
		try {
			const filters: any = {
				operation_type: operationType,
				invoice_number: searchTerm || undefined,
				status: status || undefined
			};
			// Do NOT filter by invoice_type here: restricting to TEM or DEF based on
			// the current movement_type_import value would hide valid invoices of the
			// other type. Let the user search freely and pick the right one.

			console.log('🔍 [Modal] Buscando facturas...', { activeCompanyId, filters });

			const res = await invoicesApi.list(activeCompanyId, 1, 50, filters);
			console.log('✅ [Modal] Respuesta recibida:', res);
			if (res.data) {
				invoices = res.data.items || [];
			}
		} catch (e) {
			console.error('Error searching invoices:', e);
			toast.error(m.invoice_selectors_invoice_selector_modal_search_error());
		} 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-3xl max-h-[85vh] flex flex-col p-0 overflow-hidden bg-slate-50 dark:bg-zinc-950 border-zinc-200 dark:border-zinc-800">
		<Dialog.Header class="p-6 pb-2">
			<div class="flex items-center gap-2 mb-1">
				<div class="p-1.5 bg-zinc-100 dark:bg-zinc-800 rounded-lg">
					<FileText class="w-5 h-5 text-zinc-900 dark:text-zinc-100" />
				</div>
				<Dialog.Title class="text-xl font-bold tracking-tight">
					{operationType === 'exp'
						? m.invoice_selectors_invoice_selector_modal_title_export()
						: m.invoice_selectors_invoice_selector_modal_title_import({ regimen })}
				</Dialog.Title>
			</div>
			<Dialog.Description class="text-sm text-muted-foreground ml-9">
				{#if operationType === 'exp'}
					{m.invoice_selectors_invoice_selector_modal_description_export()}
				{:else}
					{m.invoice_selectors_invoice_selector_modal_description_import({ regimen })}
				{/if}
			</Dialog.Description>
		</Dialog.Header>

		<div class="px-6 py-2">
			<div class="flex gap-2">
				<div class="relative flex-1 group">
					<Search class="absolute top-1/2 left-3 -translate-y-1/2 h-4 w-4 text-zinc-400 transition-colors group-focus-within:text-blue-500" />
					<Input
						placeholder={m.invoice_selectors_invoice_selector_modal_search_placeholder()}
						class="h-11 pl-10 bg-white dark:bg-zinc-900 border-zinc-200 dark:border-zinc-800 shadow-sm focus:ring-2 focus:ring-blue-500/20 transition-all"
						bind:value={searchTerm}
						onkeydown={(e) => e.key === 'Enter' && searchInvoices()}
					/>
				</div>
				<Button class="h-11 px-6 font-semibold" onclick={searchInvoices} disabled={loading}>
					{#if loading}
						<Loader2 class="mr-2 h-4 w-4 animate-spin" />
					{/if}
					{loading
						? m.invoice_selectors_invoice_selector_modal_searching_button()
						: m.invoice_selectors_invoice_selector_modal_search_button()}
				</Button>
			</div>
		</div>

		<div class="flex-1 overflow-y-auto px-6 py-4">
			<div class="grid grid-cols-1 gap-2">
				{#if loading && invoices.length === 0}
					<div class="flex flex-col items-center justify-center py-20 text-muted-foreground animate-pulse">
						<Loader2 class="w-8 h-8 animate-spin mb-4 text-blue-500" />
						<p class="text-sm font-medium">{m.invoice_selectors_invoice_selector_modal_searching_available()}</p>
					</div>
				{:else if invoices.length === 0}
					<div class="flex flex-col items-center justify-center py-20 text-zinc-400 bg-white dark:bg-zinc-900 rounded-xl border border-dashed border-zinc-200 dark:border-zinc-800">
						<Search class="w-8 h-8 mb-2 opacity-20" />
						<p class="text-sm font-medium">{m.invoice_selectors_invoice_selector_modal_no_invoices()}</p>
						<p class="text-xs">{m.invoice_selectors_invoice_selector_modal_try_other_filter()}</p>
					</div>
				{:else}
					{#each invoices as invoice (invoice.id)}
						<button
							class="group flex items-center justify-between p-4 bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-800 rounded-xl hover:border-blue-500 dark:hover:border-blue-600 hover:shadow-md transition-all text-left"
							onclick={() => handleSelect(invoice)}
						>
							<div class="flex items-center gap-4">
								<div class="flex flex-col gap-1">
									<div class="flex items-center gap-2">
										<span class="text-sm font-bold text-zinc-900 dark:text-zinc-100 group-hover:text-blue-600 dark:group-hover:text-blue-400 transition-colors">
											{invoice.invoice_number}
										</span>
										{#if operationType === 'imp'}
											<span class="inline-flex items-center rounded-full bg-emerald-100 dark:bg-emerald-900/40 px-2 py-0.5 text-[10px] font-bold text-emerald-700 dark:text-emerald-300 uppercase">
												{m.invoice_selectors_invoice_selector_modal_processed_badge()}
											</span>
										{/if}
									</div>
									<div class="flex items-center gap-3 text-xs text-muted-foreground">
										<div class="flex items-center gap-1">
											<Hash class="w-3 h-3" />
											{m.invoice_selectors_invoice_selector_modal_pedimento_label()}:
											<span class="text-zinc-600 dark:text-zinc-400 font-medium">
												{invoice.compliance_mx?.pedimento_r1 ||
													invoice.compliance_mx?.pedimento_id ||
													m.invoice_selectors_invoice_selector_modal_not_available_short()}
											</span>
										</div>
										<div class="flex items-center gap-1">
											<Calendar class="w-3 h-3" />
											{invoice.invoice_date
												? new Date(invoice.invoice_date).toLocaleDateString()
												: m.invoice_selectors_invoice_selector_modal_no_date()}
										</div>
									</div>
								</div>
							</div>
							<div class="opacity-0 group-hover:opacity-100 transition-opacity">
								<Button variant="ghost" size="sm" class="text-xs font-bold uppercase tracking-wider text-blue-600 dark:text-blue-400">
									{m.invoice_selectors_invoice_selector_modal_select()}
								</Button>
							</div>
						</button>
					{/each}
				{/if}
			</div>
		</div>

		<Dialog.Footer class="p-4 bg-white dark:bg-zinc-950 border-t border-zinc-200 dark:border-zinc-800 flex items-center justify-between px-6">
			<p class="text-[10px] text-muted-foreground font-medium uppercase tracking-widest">
				{m.invoice_selectors_invoice_selector_modal_total_found({ count: String(invoices.length) })}
			</p>
			<div class="flex items-center gap-2">
				{#if onClear}
					<Button
						variant="ghost"
						size="sm"
						class="text-xs font-semibold"
						onclick={() => {
							onClear();
							open = false;
						}}
					>
						Quitar selección
					</Button>
				{/if}
				<Button variant="ghost" size="sm" class="text-xs font-semibold" onclick={() => (open = false)}>
					{m.invoice_selectors_invoice_selector_modal_close()}
				</Button>
			</div>
		</Dialog.Footer>
	</Dialog.Content>
</Dialog.Root>
