<script lang="ts">
	import { onMount } from 'svelte';
	import { page } from '$app/stores';
	import { goto } from '$app/navigation';
	import InvoiceDownloadModal from '$lib/components/dashboard/invoices/invoice-download-modal.svelte';
	import TransferenciaElectronicaModal from '$lib/components/dashboard/invoices/transferencia-electronica-modal.svelte';
	import { invoicesApi, type Invoice, type OperationType } from '$lib/api/dashboard/a76/invoices';
	import { invoicesReportsApi } from '$lib/api/dashboard/a76/reports/reports-invoices';
	import { consolidatedReportsApi } from '$lib/api/dashboard/a76/reports/reports-consolidated';
	import { dischargeReportsApi } from '$lib/api/dashboard/a76/reports/reports-descargo';
	import { avisoConsolidadoReportsApi } from '$lib/api/dashboard/a76/reports/reports-aviso-consolidado';
	import DataTable from '$lib/components/dashboard/invoices/data-table.svelte';
	import { createColumns } from '$lib/components/dashboard/invoices/columns.js';
	import * as Card from '$lib/components/ui/card';
	import { Button } from '$lib/components/ui/button';
	import { Input } from '$lib/components/ui/input';
	import { Label } from '$lib/components/ui/label';
	import type { PageData } from './$types';
	import { browser } from '$app/environment';
	import { companyStore } from '$lib/stores/company.svelte';
	import {
		Plus,
		RefreshCw,
		FileText,
		RotateCcw,
		Boxes,
		Package,
		ClipboardList,
		Settings,
		Send
	} from 'lucide-svelte';

	// IMPORTANTE: Asegúrate de tener instalada svelte-sonner para las notificaciones
	import { toast } from 'svelte-sonner';
	import PdfProgressDialog from '$lib/components/dashboard/invoices/pdf-progress-dialog.svelte';
	import { useShortcuts } from '$lib/hooks/use-shortcuts';
	import { obtenerAtajosListaFacturas } from '$lib/config/shortcuts/dashboard/invoices/list';

	// Los datos iniciales vienen del servidor
	let { data }: { data: PageData } = $props();

	// Estado para filtros
	// Nota: Los query parameters invoice_type y operation_type se pueden usar para filtrar
	// Ejemplo: /dashboard/invoices?invoice_type=TEM&operation_type=imp
	let filters = $state({
		operation_type: (data.filters?.operation_type || '') as '' | OperationType,
		invoice_type: data.filters?.invoice_type || '',
		invoice_number: data.filters?.invoice_number || '',
		project_number: data.filters?.project_number || '',
		year: data.filters?.year || ''
	});

	let isDownloadModalOpen = $state(false);
	let isTransferenciaModalOpen = $state(false);

	// Efecto reactivo para actualizar filtros cuando cambian los query parameters en la URL
	$effect(() => {
		if (browser) {
			const searchParams = $page.url.searchParams;
			const urlOperationType = searchParams.get('operation_type');
			const urlInvoiceType = searchParams.get('invoice_type');
			const urlInvoiceNumber = searchParams.get('invoice_number');
			const urlProjectNumber = searchParams.get('project_number');
			const urlYear = searchParams.get('year');

			// Actualizar filtros si hay cambios en la URL
			filters.operation_type = (urlOperationType || '') as '' | OperationType;
			filters.invoice_type = urlInvoiceType || '';
			filters.invoice_number = urlInvoiceNumber || '';
			filters.project_number = urlProjectNumber || '';
			filters.year = urlYear || '';
		}
	});

	// Efecto para limpiar invoice_type si no es válido para el operation_type seleccionado
	$effect(() => {
		if (filters.invoice_type && filters.operation_type) {
			const selectedOption = allInvoiceTypeOptions().find(
				(opt) => opt.value === filters.invoice_type
			);
			if (
				selectedOption &&
				selectedOption.operation !== 'both' &&
				selectedOption.operation !== filters.operation_type
			) {
				// El tipo de factura seleccionado no es válido para esta operación
				filters.invoice_type = '';
			}
		}
	});

	// Efecto para actualizar la URL cuando cambien los filtros
	$effect(() => {
		if (browser) {
			const params = new URLSearchParams();

			if (filters.operation_type) params.set('operation_type', filters.operation_type);
			if (filters.invoice_type) params.set('invoice_type', filters.invoice_type);
			if (filters.invoice_number) params.set('invoice_number', filters.invoice_number);
			if (filters.project_number) params.set('project_number', filters.project_number);
			if (filters.year) params.set('year', filters.year);

			const queryString = params.toString();
			const newUrl = queryString ? `?${queryString}` : window.location.pathname;

			// Solo actualizar si la URL es diferente (evitar loops infinitos)
			if (window.location.search !== (queryString ? `?${queryString}` : '')) {
				window.history.replaceState({}, '', newUrl);
			}
		}
	});

	// Efecto para aplicar filtros automáticamente cuando cambian
	let filterTimeout: ReturnType<typeof setTimeout> | null = null;
	$effect(() => {
		// Observar cambios en los filtros
		const _ = {
			operation_type: filters.operation_type,
			invoice_type: filters.invoice_type,
			invoice_number: filters.invoice_number,
			project_number: filters.project_number,
			year: filters.year
		};

		// Debounce para evitar múltiples llamadas rápidas
		if (filterTimeout) clearTimeout(filterTimeout);
		filterTimeout = setTimeout(() => {
			applyFilters();
		}, 300); // Esperar 300ms después del último cambio
	});

	// Sincronizar token de cookies a localStorage al montar el componente
	onMount(() => {
		if (browser) {
			// Función para obtener el valor de una cookie
			const getCookie = (name: string): string | null => {
				const value = `; ${document.cookie}`;
				const parts = value.split(`; ${name}=`);
				if (parts.length === 2) return parts.pop()?.split(';').shift() || null;
				return null;
			};

			// Verificar si hay token en las cookies
			const cookieToken = getCookie('access_token');
			const localToken = localStorage.getItem('access_token');

			if (cookieToken && cookieToken !== localToken) {
				localStorage.setItem('access_token', cookieToken);
			}

			// También sincronizar refresh_token si existe
			const cookieRefreshToken = getCookie('refresh_token');
			const localRefreshToken = localStorage.getItem('refresh_token');

			if (cookieRefreshToken && cookieRefreshToken !== localRefreshToken) {
				localStorage.setItem('refresh_token', cookieRefreshToken);
			}

			// Escuchar cambios de compañía
			const handleCompanyChange = (event: CustomEvent) => {
				// Recargar los datos sin recargar la página completa
				reloadData();
			};

			window.addEventListener('companyChanged', handleCompanyChange as EventListener);

			// Cleanup
			return () => {
				window.removeEventListener('companyChanged', handleCompanyChange as EventListener);
			};
		}
	});

	// Estado para infinite scroll
	let allItems = $state<Invoice[]>(data.items || []);
	let currentPage = $state(data.page);
	let pageSize = $state(50);
	let totalItems = $state(data.total || 0);
	let loading = $state(false);
	let hasMore = $derived(allItems.length < totalItems);
	let error = $state<string | null>(data.error || null);

	// Estado para selección de fila
	let selectedInvoiceId = $state<number | null>(null);

	function handleRowClick(invoice: Invoice) {
		// Si ya está seleccionado, lo deseleccionamos (opcional, si queremos permitir toggle)
		// O simplemente lo seleccionamos. Aquí implemento toggle.
		if (selectedInvoiceId === invoice.id) {
			selectedInvoiceId = null;
		} else {
			selectedInvoiceId = invoice.id;
		}
	}

	const selectedInvoice = $derived(
		selectedInvoiceId ? allItems.find((i) => i.id === selectedInvoiceId) : null
	);

	async function loadMore() {
		if (loading || !hasMore) return;

		loading = true;
		error = null;

		try {
			const companyId = companyStore.activeCompany?.id;
			if (!companyId) {
				error = 'No hay compañía seleccionada';
				return;
			}

			const filterParams = {
				operation_type: filters.operation_type || undefined,
				invoice_type: filters.invoice_type || undefined,
				invoice_number: filters.invoice_number || undefined,
				project_number: filters.project_number || undefined,
				year: filters.year || undefined
			};

			const response = await invoicesApi.list(companyId, currentPage + 1, pageSize, filterParams);

			if (response.error) {
				console.error(
					'📊 [Invoices] Error en loadMore:',
					response.error,
					'Status:',
					response.status
				);

				if (response.status === 401 || response.status === 403) {
					error = 'Sesión expirada. Recargando página...';
					setTimeout(() => {
						window.location.reload();
					}, 2000);
				} else {
					error = response.error;
				}
				return;
			}

			if (response.data?.items) {
				// Agregar los nuevos items al array existente
				allItems = [...allItems, ...response.data.items];
				currentPage++;
				totalItems = response.data.total;
			}
		} catch (e) {
			error = 'Error cargando más datos';
			console.error('📊 [Invoices] Error loading more:', e);
		} finally {
			loading = false;
		}
	}

	async function applyFilters() {
		// Reset y recargar con filtros
		loading = true;
		error = null;

		try {
			const companyId = companyStore.activeCompany?.id;
			if (!companyId) {
				error = 'No hay compañía seleccionada';
				return;
			}

			// Construir query parameters para el endpoint
			// Los filtros se mapean a los parámetros del API
			const filterParams = {
				operation_type: filters.operation_type || undefined,
				invoice_type: filters.invoice_type || undefined,
				invoice_number: filters.invoice_number || undefined,
				project_number: filters.project_number || undefined,
				year: filters.year || undefined
			};

			const response = await invoicesApi.list(companyId, 1, pageSize, filterParams);

			if (response.error) {
				console.error('📊 [Invoices] Error aplicando filtros:', response.error);

				if (response.status === 401 || response.status === 403) {
					error = 'Sesión expirada. Recargando página...';
					setTimeout(() => {
						window.location.reload();
					}, 2000);
				} else {
					error = response.error;
				}
				return;
			}

			if (response.data) {
				allItems = response.data.items;
				currentPage = 1;
				totalItems = response.data.total;
			}
		} catch (e) {
			error = 'Error aplicando filtros';
			console.error('📊 [Invoices] Error applying filters:', e);
		} finally {
			loading = false;
		}
	}

	function clearFilters() {
		filters = {
			operation_type: '',
			invoice_type: '',
			invoice_number: '',
			project_number: '',
			year: ''
		};
		applyFilters();
	}

	async function reloadData() {
		// Reset y recargar desde el principio usando la API
		if (!companyStore.activeCompany) return;

		loading = true;
		error = null;

		try {
			const companyId = companyStore.activeCompany.id;

			const filterParams = {
				operation_type: filters.operation_type || undefined,
				invoice_type: filters.invoice_type || undefined,
				invoice_number: filters.invoice_number || undefined,
				project_number: filters.project_number || undefined,
				year: filters.year || undefined
			};

			const response = await invoicesApi.list(companyId, 1, pageSize, filterParams);

			if (response.error) {
				console.error('📊 [Invoices] Error en reloadData:', response.error);
				if (response.status === 401 || response.status === 403) {
					error = 'Sesión expirada. Recargando página...';
					setTimeout(() => {
						window.location.reload();
					}, 2000);
				} else {
					error = response.error;
				}
				return;
			}

			if (response.data?.items) {
				// Reemplazar todos los items con los nuevos datos
				allItems = response.data.items;
				currentPage = 1;
				totalItems = response.data.total;
			}
		} catch (e) {
			error = 'Error recargando datos';
			console.error('📊 [Invoices] Error reloading:', e);
		} finally {
			loading = false;
		}
	}

	// Estado para el diálogo de progreso
	let showProgressDialog = $state(false);
	let currentTaskId = $state<string | null>(null);
	let currentStatusFunction = $state<((taskId: string) => Promise<any>) | null>(null);

	// Utilidad para convertir Base64 a Blob
	function base64ToBlob(base64: string, type: string) {
		const binStr = atob(base64);
		const len = binStr.length;
		const arr = new Uint8Array(len);
		for (let i = 0; i < len; i++) {
			arr[i] = binStr.charCodeAt(i);
		}
		return new Blob([arr], { type: type });
	}

	async function handleDownloadPdf(invoice: any) {
		if (!companyStore.activeCompany) {
			toast.error('No hay empresa seleccionada');
			return;
		}

		try {
			// 1. Trigger: Iniciar la tarea en Celery
			const { task_id } = await invoicesReportsApi.triggerPdfGeneration(
				invoice.id,
				companyStore.activeCompany.id
			);

			// 2. Abrir diálogo de progreso
			currentTaskId = task_id;
			currentStatusFunction = invoicesReportsApi.getTaskStatus;
			showProgressDialog = true;
		} catch (error) {
			console.error(error);
			toast.error('No se pudo iniciar la descarga');
		}
	}

	async function handleDownloadConsolidated(invoice: any) {
		if (!companyStore.activeCompany) {
			toast.error('No hay empresa seleccionada');
			return;
		}

		try {
			// 1. Trigger: Iniciar la tarea en Celery (Consolidado Importación)
			const { task_id } = await consolidatedReportsApi.triggerPdfGeneration(
				invoice.id,
				companyStore.activeCompany.id
			);

			// 2. Abrir diálogo de progreso
			currentTaskId = task_id;
			currentStatusFunction = consolidatedReportsApi.getTaskStatus;
			showProgressDialog = true;
		} catch (error) {
			console.error(error);
			toast.error('No se pudo iniciar la descarga del consolidado');
		}
	}

	async function handleDownloadDescargo(invoice: any) {
		if (!companyStore.activeCompany) {
			toast.error('No hay empresa seleccionada');
			return;
		}

		try {
			// 0. Trigger: Ejecutar Asignación PEPS (FIFO)
			toast.info('Calculando asignación PEPS...');
			const fifoResponse = await dischargeReportsApi.assignFifo(invoice.id);

			if (fifoResponse.error) {
				toast.error('Error al calcular PEPS: ' + fifoResponse.error);
				return;
			}
			toast.success('Cálculo PEPS completado');

			// 1. Trigger: Iniciar la tarea en Celery
			const { task_id } = await dischargeReportsApi.triggerPdfGeneration(
				invoice.id,
				companyStore.activeCompany.id
			);

			// 2. Abrir diálogo de progreso
			currentTaskId = task_id;
			currentStatusFunction = dischargeReportsApi.getTaskStatus;
			showProgressDialog = true;
		} catch (error) {
			console.error(error);
			toast.error('No se pudo iniciar la descarga del reporte PEPS');
		}
	}

	async function handleDownloadAvisoConsolidado(invoice: any) {
		if (!companyStore.activeCompany) {
			toast.error('No hay empresa seleccionada');
			return;
		}

		try {
			// 1. Trigger: Iniciar la tarea en Celery (Aviso Consolidado Exportación)
			const { task_id } = await avisoConsolidadoReportsApi.triggerPdfGeneration(
				invoice.id,
				companyStore.activeCompany.id
			);

			// 2. Abrir diálogo de progreso
			currentTaskId = task_id;
			currentStatusFunction = avisoConsolidadoReportsApi.getTaskStatus;
			showProgressDialog = true;
		} catch (error) {
			console.error(error);
			toast.error('No se pudo iniciar la descarga del Aviso Consolidado');
		}
	}

	async function handleDownloadPackingList(invoice: any) {
		if (!companyStore.activeCompany) {
			toast.error('No hay empresa seleccionada');
			return;
		}

		try {
			// 1. Trigger: Start task in Celery
			const { task_id } = await invoicesReportsApi.triggerPackingListGeneration(
				invoice.id,
				companyStore.activeCompany.id
			);

			// 2. Open progress dialog
			currentTaskId = task_id;
			// Use the specific status function for Packing List
			currentStatusFunction = invoicesReportsApi.getPackingListTaskStatus;
			showProgressDialog = true;
		} catch (error) {
			console.error(error);
			toast.error('No se pudo iniciar la descarga del Packing List');
		}
	}

	function onPdfComplete(result: any) {
		// Esta función se llama cuando el diálogo reporta SUCCESS
		try {
			if (result.status === 'success') {
				const blob = base64ToBlob(result.content, result.media_type);
				const url = window.URL.createObjectURL(blob);
				const a = document.createElement('a');
				a.href = url;
				a.download = result.file_name;
				document.body.appendChild(a);
				a.click();
				window.URL.revokeObjectURL(url);
				document.body.removeChild(a);
				toast.success('PDF Descargado exitosamente');
			} else {
				toast.error('El worker reportó un error: ' + (result.message || 'Desconocido'));
			}
		} catch (e) {
			console.error('Error al procesar descarga:', e);
			toast.error('Error al procesar el archivo descargado');
		} finally {
			// Cerrar diálogo después de un breve momento
			setTimeout(() => {
				showProgressDialog = false;
				currentTaskId = null;
			}, 1000);
		}
	}

	function handleCreateClick() {
		const params = new URLSearchParams(window.location.search);

		const queryString = params.toString();
		const url = queryString
			? `/dashboard/invoices/edit/new?${queryString}`
			: '/dashboard/invoices/edit/new';

		window.location.href = url;
	}

	function handleEditSelected() {
		if (selectedInvoice) {
			const params = new URLSearchParams(window.location.search);
			const queryString = params.toString();
			const url = queryString
				? `/dashboard/invoices/edit/${selectedInvoice.id}?${queryString}`
				: `/dashboard/invoices/edit/${selectedInvoice.id}`;
			window.location.href = url;
		} else {
			toast.info('Seleccione una factura para editar');
		}
	}

	useShortcuts(
		'Invoices List',
		obtenerAtajosListaFacturas({
			manejarCrear: handleCreateClick,
			manejarActualizar: reloadData,
			manejarEditar: handleEditSelected,
			manejarDescargarPdf: () => {
				if (selectedInvoice) handleDownloadPdf(selectedInvoice);
				else toast.info('Seleccione una factura para descargar PDF');
			},
			manejarDescargarConsolidado: () => {
				if (selectedInvoice) handleDownloadConsolidated(selectedInvoice);
				else toast.info('Seleccione una factura para descargar consolidado');
			},
			irTemporal: () => goto('/dashboard/invoices?operation_type=imp&invoice_type=TEM'),
			irDefinitiva: () => goto('/dashboard/invoices?operation_type=imp&invoice_type=DEF'),
			irNacional: () => goto('/dashboard/invoices?operation_type=imp&invoice_type=MEX'),
			irCambioRegimen: () => goto('/dashboard/invoices?operation_type=imp&invoice_type=CR'),
			irExportacion: () => goto('/dashboard/invoices?operation_type=exp'),
			irReparacion: () => goto('/dashboard/invoices?operation_type=exp&invoice_type=REPAR')
		})
	);

	function handleSuccess() {
		reloadData();
	}

	async function handleUpdateStatus(status: boolean) {
		if (!selectedInvoice || !companyStore.activeCompany) {
			toast.info('Seleccione una factura para cambiar su estatus');
			return;
		}

		loading = true;
		try {
			const companyId = companyStore.activeCompany.id;
			const response = await invoicesApi.update(selectedInvoice.id, companyId, {
				id: selectedInvoice.id,
				is_updated: status
			});

			if (response.error) {
				toast.error(
					`Error al ${status ? 'actualizar' : 'desactualizar'} factura: ${response.error}`
				);
			} else {
				toast.success(`Factura ${status ? 'actualizada' : 'desactualizada'} correctamente`);
				reloadData();
			}
		} catch (e) {
			console.error('Error updating status:', e);
			toast.error('Error inesperado al cambiar el estatus');
		} finally {
			loading = false;
		}
	}

	// Opciones de tipo de operación para el filtro
	const operationTypeOptions = [
		{ value: '', label: 'Todas' },
		{ value: 'imp', label: 'Importación' },
		{ value: 'exp', label: 'Exportación' }
	];

	// Todas las opciones de tipo de factura con su operación correspondiente
	const allInvoiceTypeOptions = $derived(() => {
		const options = [{ value: '', label: 'Todas', operation: 'both' }];
		if (data.invoiceTypes) {
			data.invoiceTypes.forEach((type: any) => {
				options.push({
					value: type.key,
					label: type.description,
					operation: type.operation
				});
			});
		}
		return options;
	});

	const invoiceTypeOptions = $derived(() => {
		const allOptions = allInvoiceTypeOptions();
		if (!filters.operation_type) {
			return allOptions;
		}
		return allOptions.filter(
			(option) => option.operation === 'both' || option.operation === filters.operation_type
		);
	});

	function closeProgressDialog() {
		showProgressDialog = false;
		currentTaskId = null;
		currentStatusFunction = null;
	}

	// --- AQUÍ PASAMOS LA FUNCIÓN DE DESCARGA A LAS COLUMNAS ---
	const columns = createColumns(handleSuccess);
	async function handleModalConfirm(
		type: string,
		format: string,
		currency: string,
		uomSource: string,
		weightUnit: string
	) {
		if (!selectedInvoice || !companyStore.activeCompany) return;

		try {
			// 1. Trigger: Start celery task with selected options
			// Note: uomSource and weightUnit are UI-only for now
			const { task_id } = await invoicesReportsApi.triggerPdfGeneration(
				selectedInvoice.id,
				companyStore.activeCompany.id,
				type,
				currency
			);

			// 2. Open Progress Dialog
			currentTaskId = task_id;
			currentStatusFunction = invoicesReportsApi.getTaskStatus;
			showProgressDialog = true;
		} catch (error) {
			console.error(error);
			toast.error('No se pudo iniciar la descarga');
		}
	}
</script>

<div class="space-y-6">
	<div class="flex items-center justify-between">
		<div>
			<h1 class="text-3xl font-bold tracking-tight">Facturas</h1>
			<p class="text-muted-foreground">Gestiona las facturas del sistema</p>
		</div>
		<div class="flex items-center gap-2">
			<Button variant="outline" onclick={() => goto('/dashboard/invoices/settings')}>
				<Settings class="mr-2" size={16} />
				Parámetros
			</Button>
			<Button onclick={handleCreateClick}>
				<Plus class="mr-2" size={16} />
				Nueva Factura
			</Button>
		</div>
	</div>

	<Card.Root>
		<Card.Header>
			<Card.Title>Filtros</Card.Title>
			<Card.Description
				>Filtra las facturas por diferentes criterios (los filtros se aplican automáticamente)</Card.Description
			>
		</Card.Header>
		<Card.Content>
			<div class="grid grid-cols-1 gap-4 md:grid-cols-5">
				<div class="space-y-2">
					<Label for="filter-operation-type">Tipo de Operación</Label>
					<select
						id="filter-operation-type"
						bind:value={filters.operation_type}
						class="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:outline-none"
					>
						{#each operationTypeOptions as option}
							<option value={option.value}>{option.label}</option>
						{/each}
					</select>
				</div>

				<div class="space-y-2">
					<Label for="filter-invoice-type">Tipo de Factura</Label>
					<select
						id="filter-invoice-type"
						bind:value={filters.invoice_type}
						class="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:outline-none"
					>
						{#each invoiceTypeOptions() as option}
							<option value={option.value}>{option.label}</option>
						{/each}
					</select>
				</div>

				<div class="space-y-2">
					<Label for="filter-invoice-number">Número de Factura</Label>
					<Input
						id="filter-invoice-number"
						bind:value={filters.invoice_number}
						placeholder="Ej: INV-2024-001"
					/>
				</div>

				<div class="space-y-2">
					<Label for="filter-project-number">Número de Proyecto</Label>
					<Input
						id="filter-project-number"
						bind:value={filters.project_number}
						placeholder="Ej: PROJ-001"
					/>
				</div>

				<div class="space-y-2">
					<Label for="filter-year">Año</Label>
					<Input id="filter-year" bind:value={filters.year} placeholder="Ej: 2024" maxlength={4} />
				</div>
			</div>
		</Card.Content>
	</Card.Root>

	{#if error}
		<Card.Root class="border-destructive">
			<Card.Header>
				<Card.Title class="text-destructive">Error</Card.Title>
				<Card.Description>{error}</Card.Description>
			</Card.Header>
		</Card.Root>
	{/if}

	<Card.Root>
		<Card.Header>
			<div class="flex items-center justify-between">
				<div>
					<Card.Title>Listado de Facturas</Card.Title>
					<Card.Description>
						Mostrando {allItems.length} de {totalItems} registros
					</Card.Description>
				</div>
				<Button variant="outline" onclick={reloadData}>
					<RefreshCw class="mr-2" size={16} />
					Actualizar
				</Button>
			</div>
		</Card.Header>
		<Card.Content>
			<DataTable
				data={allItems}
				{columns}
				{loading}
				{hasMore}
				{loadMore}
				selectedId={selectedInvoiceId}
				onRowClick={handleRowClick}
			/>
		</Card.Content>
	</Card.Root>

	<PdfProgressDialog
		bind:open={showProgressDialog}
		taskId={currentTaskId}
		getStatus={currentStatusFunction}
		onComplete={onPdfComplete}
		onClose={closeProgressDialog}
	/>

	<!-- Footer fijo con botones de acción -->
	<div
		class="fixed right-0 bottom-0 left-0 z-[5] ml-[calc(var(--sidebar-width))] border-t bg-background/95 shadow-lg backdrop-blur group-has-data-[state=collapsed]/sidebar-wrapper:ml-[calc(var(--sidebar-width-icon))] supports-[backdrop-filter]:bg-background/80"
	>
		<div class="mx-auto max-w-[1400px] px-4 py-4">
			<!-- Botones de acción -->
			<div class="flex justify-end gap-2">
				<Button
					variant="outline"
					size="sm"
					disabled={!selectedInvoice || loading}
					onclick={() => handleUpdateStatus(true)}
				>
					<RefreshCw class="mr-2 h-4 w-4" />
					Actualizar
				</Button>
				<Button
					variant="outline"
					size="sm"
					disabled={!selectedInvoice || loading}
					onclick={() => handleUpdateStatus(false)}
				>
					<RotateCcw class="mr-2 h-4 w-4" />
					Desactualizar
				</Button>
				<Button
					variant="outline"
					size="sm"
					onclick={() => (isDownloadModalOpen = true)}
					disabled={!selectedInvoice}
				>
					<FileText class="mr-2 h-4 w-4" />
					Factura
				</Button>

				<Button
					variant="outline"
					size="sm"
					onclick={() => selectedInvoice && handleDownloadConsolidated(selectedInvoice)}
					disabled={!selectedInvoice}
				>
					<Boxes class="mr-2 h-4 w-4" />
					Consolidado
				</Button>

				<Button
					variant="outline"
					size="sm"
					onclick={() => selectedInvoice && handleDownloadAvisoConsolidado(selectedInvoice)}
					disabled={!selectedInvoice}
				>
					<Boxes class="mr-2 h-4 w-4" />
					Aviso Consolidado
				</Button>

				<Button
					variant="outline"
					size="sm"
					onclick={() => selectedInvoice && handleDownloadPackingList(selectedInvoice)}
					disabled={!selectedInvoice}
				>
					<Package class="mr-2 h-4 w-4" />
					Packing List
				</Button>

				<Button
					variant="outline"
					size="sm"
					onclick={() => (isTransferenciaModalOpen = true)}
					disabled={!companyStore.activeCompany}
				>
					<Send class="mr-2 h-4 w-4" />
					Transferencia Electrónica
				</Button>

				{#if selectedInvoice?.operation_type === 'exp'}
					<Button
						variant="outline"
						size="sm"
						onclick={() => selectedInvoice && handleDownloadDescargo(selectedInvoice)}
						disabled={!selectedInvoice}
					>
						<ClipboardList class="mr-2 h-4 w-4" />
						Descargo PEPS
					</Button>
				{/if}
			</div>
		</div>
	</div>

	<!-- ... -->

	{#if companyStore.activeCompany}
		<InvoiceDownloadModal bind:open={isDownloadModalOpen} onConfirm={handleModalConfirm} />
		<TransferenciaElectronicaModal bind:open={isTransferenciaModalOpen} invoice={selectedInvoice} />
	{/if}
</div>
