<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 { reportsTransmissionApi } from '$lib/api/dashboard/a76/reports/reports-transmission';
	import { reportsWinsaaiApi } from '$lib/api/dashboard/a76/reports/reports-winsaai';
	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 * as AlertDialog from '$lib/components/ui/alert-dialog';
	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,
		Eye,
		Pencil,
		Trash2,
		Download,
		MonitorUp,
		Files,
		ScrollText,
		BadgeCent,
		ArrowRightLeft,
		Database,
		ChevronUp
	} from 'lucide-svelte';
	import DetailsDialog from '$lib/components/dashboard/invoices/details-dialog.svelte';
	import DeleteDialog from '$lib/components/dashboard/invoices/delete-dialog.svelte';
	import * as DropdownMenu from '$lib/components/ui/dropdown-menu';

	// IMPORTANTE: Asegúrate de tener instalada svelte-sonner para las notificaciones
	import { toast } from 'svelte-sonner';
	import { fly } from 'svelte/transition';
	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);
	let isRevertConfirmOpen = $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;
	let lastFiltersKey = '';
	$effect(() => {
		// Observar cambios en los filtros
		const currentFilters = {
			operation_type: filters.operation_type,
			invoice_type: filters.invoice_type,
			invoice_number: filters.invoice_number,
			project_number: filters.project_number,
			year: filters.year
		};
		const currentFiltersKey = JSON.stringify(currentFilters);

		// Limpiar selección cada vez que se modifica algún filtro
		if (currentFiltersKey !== lastFiltersKey) {
			selectedInvoiceIds = [];
			lastFiltersKey = currentFiltersKey;
		}

		// 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 filas (múltiple)
	let selectedInvoiceIds = $state<number[]>([]);
	// Estado para los diálogos de acciones
	let showDetailsDialog = $state(false);
	let showDeleteDialog = $state(false);

	function handleRowClick(invoice: Invoice) {
		const id = invoice.id;
		if (selectedInvoiceIds.includes(id)) {
			// Deseleccionar si ya estaba
			selectedInvoiceIds = selectedInvoiceIds.filter((selectedId) => selectedId !== id);
		} else {
			// Seleccionar agregando a la lista
			selectedInvoiceIds = [...selectedInvoiceIds, id];
		}
	}

	const selectedInvoice = $derived(
		selectedInvoiceIds.length === 1 ? allItems.find((i) => i.id === selectedInvoiceIds[0]) : null
	);

	const hasSelection = $derived(selectedInvoiceIds.length > 0);

	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 isWinsaiiConfirmOpen = $state(false);
	let currentTaskId = $state<string | null>(null);
	let currentStatusFunction = $state<((taskId: string) => Promise<any>) | null>(null);
	let progressDialogTitle = $state('Generando documento');

	// 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;
			progressDialogTitle = 'Generando PDF de Factura';
			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;
			progressDialogTitle = 'Generando Consolidado';
			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;
			progressDialogTitle = 'Generando Reporte PEPS';
			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;
			progressDialogTitle = 'Generando Aviso Consolidado';
			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;
			progressDialogTitle = 'Generando Packing List';
			showProgressDialog = true;
		} catch (error) {
			console.error(error);
			toast.error('No se pudo iniciar la descarga del Packing List');
		}
	}

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

		if (invoice.operation_type !== 'imp') {
			toast.info('La interfaz rápida solo está disponible para facturas de Importación');
			return;
		}

		// Abrir confirmación
		isWinsaiiConfirmOpen = true;
	}

	async function confirmWinsaiiGeneration() {
		if (!selectedInvoice) return;
		isWinsaiiConfirmOpen = false;

		try {
			const res = await reportsWinsaaiApi.invoices.triggerGeneration({
				invoice_ids: [selectedInvoice.id],
				is_temporal: selectedInvoice.invoice_type === 'TEM'
			});

			if (res.task_id) {
				currentTaskId = res.task_id;
				// Use the specific status and download functions for WINSAAI
				currentStatusFunction = reportsWinsaaiApi.invoices.getTaskStatus;
				progressDialogTitle = 'Generando Reporte WINSAAI';
				showProgressDialog = true;
			}
		} catch (error) {
			console.error(error);
			toast.error('No se pudo iniciar la generación de Interface Agente Aduanal');
		}
	}

	function onPdfComplete(result: any) {
		// Esta función se llama cuando el diálogo reporta SUCCESS
		try {
			if (result.status === 'success') {
				if (result.content) {
					// Resultado de generación de PDF: descargar archivo
					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 {
					// Resultado de procesamiento de factura
					toast.success('Factura procesada correctamente');
					reloadData();
				}
			} else if (result.status === 'validation_error') {
				const errors: any[] = result.errors || [];
				const preview = errors
					.slice(0, 3)
					.map((e: any) => `• ${e.message}`)
					.join('\n');
				const extra = errors.length > 3 ? `\n...y ${errors.length - 3} más` : '';
				toast.error(`${errors.length} error(es) de validación:\n${preview}${extra}`);
			} else {
				toast.error('El worker reportó un error: ' + (result.message || 'Desconocido'));
			}
		} catch (e) {
			console.error('Error al procesar resultado:', e);
			toast.error('Error al procesar el resultado de la tarea');
		} 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,
				status: 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;
		}
	}

	async function handleProcessInvoice() {
		if (!selectedInvoice || !companyStore.activeCompany) {
			toast.info('Selecciona una factura para procesar');
			return;
		}

		try {
			const response = await invoicesApi.processInvoice(
				selectedInvoice.id,
				companyStore.activeCompany.id
			);

			if (response.error) {
				toast.error(`Error al iniciar el proceso: ${response.error}`);
				return;
			}

			currentTaskId = response.data!.task_id;
			currentStatusFunction = invoicesApi.getProcessStatus;
			progressDialogTitle = 'Procesando factura';
			showProgressDialog = true;
		} catch (e) {
			console.error('Error al iniciar proceso de factura:', e);
			toast.error('No se pudo iniciar el proceso');
		}
	}

	async function confirmRevertInvoice() {
		if (!selectedInvoice || !companyStore.activeCompany) return;
		isRevertConfirmOpen = false;

		try {
			const response = await invoicesApi.revertInvoice(
				selectedInvoice.id,
				companyStore.activeCompany.id
			);

			if (response.error) {
				toast.error(`Error al iniciar la des-actualización: ${response.error}`);
				return;
			}

			currentTaskId = response.data!.task_id;
			currentStatusFunction = invoicesApi.getRevertStatus;
			progressDialogTitle = 'Des-actualizando factura';
			showProgressDialog = true;
		} catch (e) {
			console.error('Error al iniciar des-actualización de factura:', e);
			toast.error('No se pudo iniciar la des-actualización');
		}
	}

	// Pasos del procesamiento de factura (deben coincidir con el backend)
	const invoiceProcessSteps = [
		{ label: 'Cargando factura', percent: 5 },
		{ label: 'Validando datos de la factura', percent: 10 },
		{ label: 'Revisando clases y tipo de cambio', percent: 30 },
		{ label: 'Calculando valores por partida', percent: 50 },
		{ label: 'Validando partidas', percent: 70 },
		{ label: 'Validando cupos de Regla Octava', percent: 85 },
		{ label: 'Actualizando totales', percent: 95 }
	];

	const invoiceRevertSteps = [
		{ label: 'Cargando factura', percent: 5 },
		{ label: 'Validando estatus de la factura', percent: 10 },
		{ label: 'Verificando saldos de partidas', percent: 40 },
		{ label: 'Confirmando cambios', percent: 95 }
	];

	// 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>
				<div class="flex items-center gap-2">
					<Button variant="outline" onclick={reloadData}>
						<RefreshCw class="mr-2" size={16} />
						Actualizar
					</Button>
				</div>
			</div>
		</Card.Header>
		<Card.Content>
			<DataTable
				data={allItems}
				{columns}
				{loading}
				{hasMore}
				{loadMore}
				selectedIds={selectedInvoiceIds}
				onRowClick={handleRowClick}
			/>
		</Card.Content>
	</Card.Root>

	<PdfProgressDialog
		bind:open={showProgressDialog}
		taskId={currentTaskId}
		getStatus={currentStatusFunction}
		onComplete={onPdfComplete}
		onClose={closeProgressDialog}
		title={progressDialogTitle}
		steps={
			progressDialogTitle === 'Procesando factura'
				? invoiceProcessSteps
				: progressDialogTitle === 'Des-actualizando factura'
					? invoiceRevertSteps
					: []
		}
		completeMessage={
			progressDialogTitle === 'Procesando factura'
				? 'Factura procesada correctamente'
				: progressDialogTitle === 'Des-actualizando factura'
					? 'Factura des-actualizada correctamente'
					: 'Listo para descargar'
		}
	/>

	<AlertDialog.Root bind:open={isRevertConfirmOpen}>
		<AlertDialog.Content>
			<AlertDialog.Header>
				<AlertDialog.Title>
					Des-actualizar Factura de {selectedInvoice?.operation_type === 'exp' ? 'Exportación' : 'Importación'}
				</AlertDialog.Title>
				<AlertDialog.Description>
					Se va a des-actualizar la factura <strong>{selectedInvoice?.invoice_number}</strong>.
					Esta operación revertirá los registros de saldos/descargos generados al procesar la factura.
					¿Desea continuar?
				</AlertDialog.Description>
			</AlertDialog.Header>
			<AlertDialog.Footer>
				<AlertDialog.Cancel>Cancelar</AlertDialog.Cancel>
				<AlertDialog.Action onclick={confirmRevertInvoice}>Continuar</AlertDialog.Action>
			</AlertDialog.Footer>
		</AlertDialog.Content>
	</AlertDialog.Root>

	<AlertDialog.Root bind:open={isWinsaiiConfirmOpen}>
		<AlertDialog.Content>
			<AlertDialog.Header>
				<AlertDialog.Title>Sistema de Control de Aduanas e Inventarios</AlertDialog.Title>
				<AlertDialog.Description>
					A la Factura <strong>{selectedInvoice?.invoice_number}</strong> de tipo
					<strong>{selectedInvoice?.document_type}</strong> se le ha asignado el proceso Generación del
					Archivo WINSAAI. ¿Desea Continuar o Cancelar?
				</AlertDialog.Description>
			</AlertDialog.Header>
			<AlertDialog.Footer>
				<AlertDialog.Cancel>Cancelar</AlertDialog.Cancel>
				<AlertDialog.Action onclick={confirmWinsaiiGeneration}>Continuar</AlertDialog.Action>
			</AlertDialog.Footer>
		</AlertDialog.Content>
	</AlertDialog.Root>

	<!-- 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 w-full items-center justify-end gap-2">
				{#if hasSelection}
					<div transition:fly={{ x: 40, duration: 250 }} class="flex items-center gap-2">
						<!-- Dropdown: Reportes -->
						<DropdownMenu.Root>
							<DropdownMenu.Trigger>
								{#snippet child({ props })}
									<Button
										{...props}
										variant="outline"
										size="sm"
										disabled={selectedInvoiceIds.length !== 1}
									>
										Reportes
										<ChevronUp class="ml-2 h-4 w-4" />
									</Button>
								{/snippet}
							</DropdownMenu.Trigger>
							<DropdownMenu.Content align="end" class="max-h-[400px] w-56 overflow-y-auto">
								<DropdownMenu.Group>
									<DropdownMenu.Label>Descargas</DropdownMenu.Label>
									<DropdownMenu.Item onclick={() => (isDownloadModalOpen = true)}>
										<FileText class="mr-2 h-4 w-4" />
										Factura PDF
									</DropdownMenu.Item>
									<DropdownMenu.Item
										onclick={() => toast.info('Generar Factura CSV - Próximamente')}
									>
										<Download class="mr-2 h-4 w-4" />
										Factura CSV
									</DropdownMenu.Item>
									<DropdownMenu.Item
										onclick={() => selectedInvoice && handleDownloadConsolidated(selectedInvoice)}
									>
										<Boxes class="mr-2 h-4 w-4" />
										Consolidado
									</DropdownMenu.Item>
									<DropdownMenu.Item
										onclick={() =>
											selectedInvoice && handleDownloadAvisoConsolidado(selectedInvoice)}
									>
										<Boxes class="mr-2 h-4 w-4" />
										Aviso Consolidado
									</DropdownMenu.Item>
									<DropdownMenu.Item
										onclick={() => selectedInvoice && handleDownloadPackingList(selectedInvoice)}
									>
										<Package class="mr-2 h-4 w-4" />
										Packing List
									</DropdownMenu.Item>
									<DropdownMenu.Item onclick={() => toast.info('4 Copias Rem - Próximamente')}>
										<Files class="mr-2 h-4 w-4" />
										4 Copias Rem
									</DropdownMenu.Item>
									{#if selectedInvoice?.operation_type === 'exp'}
										<DropdownMenu.Item onclick={() => handleDownloadDescargo(selectedInvoice)}>
											<ClipboardList class="mr-2 h-4 w-4" />
											Descargo PEPS
										</DropdownMenu.Item>
									{/if}
								</DropdownMenu.Group>
							</DropdownMenu.Content>
						</DropdownMenu.Root>

						<!-- Dropdown: Más Acciones -->
						<DropdownMenu.Root>
							<DropdownMenu.Trigger>
								{#snippet child({ props })}
									<Button
										{...props}
										variant="outline"
										size="sm"
										disabled={selectedInvoiceIds.length !== 1}
									>
										Más Acciones
										<ChevronUp class="ml-2 h-4 w-4" />
									</Button>
								{/snippet}
							</DropdownMenu.Trigger>
							<DropdownMenu.Content align="end" class="max-h-[400px] w-56 overflow-y-auto">
								<DropdownMenu.Group>
									<DropdownMenu.Label>Otras Acciones</DropdownMenu.Label>
									<DropdownMenu.Item
										onclick={() => (isTransferenciaModalOpen = true)}
										disabled={!companyStore.activeCompany}
									>
										<Send class="mr-2 h-4 w-4" />
										Transferencia Electrónica
									</DropdownMenu.Item>
									<DropdownMenu.Item onclick={() => toast.info('Interface VU - Próximamente')}>
										<MonitorUp class="mr-2 h-4 w-4" />
										Interface VU
									</DropdownMenu.Item>
									<DropdownMenu.Item onclick={() => toast.info('Cons SED - Próximamente')}>
										<ScrollText class="mr-2 h-4 w-4" />
										Cons SED
									</DropdownMenu.Item>
									<DropdownMenu.Item onclick={() => toast.info('Encomienda - Próximamente')}>
										<BadgeCent class="mr-2 h-4 w-4" />
										Encomienda
									</DropdownMenu.Item>
									<DropdownMenu.Item
										onclick={() => toast.info('Factura Mex Consolidada - Próximamente')}
									>
										<FileText class="mr-2 h-4 w-4" />
										Fact Mex Cons
									</DropdownMenu.Item>
									<DropdownMenu.Item
										onclick={() => toast.info('Factura Mex Orden Captura - Próximamente')}
									>
										<FileText class="mr-2 h-4 w-4" />
										Fact Mex Ord Cat
									</DropdownMenu.Item>
									<DropdownMenu.Item onclick={() => toast.info('Export SIA - Próximamente')}>
										<Database class="mr-2 h-4 w-4" />
										Export SIA
									</DropdownMenu.Item>
									<DropdownMenu.Item onclick={() => toast.info('Interface - Próximamente')}>
										<ArrowRightLeft class="mr-2 h-4 w-4" />
										Interface
									</DropdownMenu.Item>
								</DropdownMenu.Group>
							</DropdownMenu.Content>
						</DropdownMenu.Root>
						<div class="h-6 w-px bg-border"></div>
					</div>
				{/if}
				<!-- Procesa la factura seleccionada mediante tarea Celery -->
				<Button
					variant="outline"
					size="sm"
					disabled={loading || selectedInvoiceIds.length !== 1}
					onclick={handleProcessInvoice}
				>
					<RefreshCw class="mr-2 h-4 w-4" />
					Actualizar
				</Button>
				<Button
					variant="outline"
					size="sm"
					disabled={loading || selectedInvoiceIds.length !== 1}
					onclick={() => (isRevertConfirmOpen = true)}
				>
					<RotateCcw class="mr-2 h-4 w-4" />
					Desactualizar
				</Button>
				<Button
					variant="outline"
					size="sm"
					disabled={selectedInvoiceIds.length !== 1}
					onclick={() => (showDetailsDialog = true)}
				>
					<Eye class="mr-2 h-4 w-4" />
					Ver Detalles
				</Button>

				<Button
					variant="outline"
					size="sm"
					onclick={() => selectedInvoice && handleInterfaceAgenteAduanal(selectedInvoice)}
					disabled={!selectedInvoice}
				>
					<Send class="mr-2 h-4 w-4" />
					Interface Agente Aduanal
				</Button>

				<Button
					variant="outline"
					size="sm"
					disabled={selectedInvoiceIds.length !== 1}
					onclick={handleEditSelected}
				>
					<Pencil class="mr-2 h-4 w-4" />
					Editar
				</Button>
				<Button
					variant="outline"
					size="sm"
					disabled={selectedInvoiceIds.length === 0}
					onclick={() => (showDeleteDialog = true)}
				>
					<Trash2 class="mr-2 h-4 w-4" />
					Eliminar
				</Button>
			</div>
		</div>
	</div>

	<!-- ... -->

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

	{#if showDetailsDialog && selectedInvoice}
		<DetailsDialog invoice={selectedInvoice} onClose={() => (showDetailsDialog = false)} />
	{/if}

	{#if showDeleteDialog}
		<DeleteDialog
			invoice={selectedInvoice}
			invoicesToDelete={selectedInvoiceIds
				.map((id) => allItems.find((i) => i.id === id))
				.filter((i): i is Invoice => i !== undefined)}
			onClose={() => {
				showDeleteDialog = false;
				selectedInvoiceIds = [];
			}}
			onSuccess={() => {
				showDeleteDialog = false;
				selectedInvoiceIds = [];
				handleSuccess();
			}}
		/>
	{/if}
</div>
