<script lang="ts">
	import { onMount } from 'svelte';
	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 * as RadioGroup from '$lib/components/ui/radio-group';
	import { Checkbox } from '$lib/components/ui/checkbox';
	import { Separator } from '$lib/components/ui/separator';
	import {
		Printer,
		HelpCircle,
		X,
		Calendar,
		FileSearch,
		Filter,
		Globe,
		Search,
		Mail,
		Info,
		ChevronRight,
		Book,
		MapPin,
		FileText,
		Settings,
		FileSpreadsheet,
		ArrowLeftRight,
		ShieldCheck,
		Calculator,
		Download,
		Folder,
		Eye
	} from 'lucide-svelte';
	import * as DropdownMenu from '$lib/components/ui/dropdown-menu';
	import * as Dialog from '$lib/components/ui/dialog';
	import { toast } from 'svelte-sonner';
	import {
		invoiceMovementsApi,
		type MovementItem,
		type MovementItemDetailed,
		type AllMovementsFilter
	} from '$lib/api/dashboard/a76/invoice-movements';
	import type { BaseFilter } from '$lib/api/dashboard/a76/invoice-movements';
	import { api } from '$lib/api';
	import { companyStore } from '$lib/stores/company.svelte';

	// --- ESTADO CON RUNAS (SVELTE 5) ---

	const menuOptions = [
		{ label: 'Saldos Temporales', icon: Calculator, items: [] },
		{ label: 'Descargos', icon: FileSpreadsheet, items: [] },
		{
			label: 'Catálogos',
			icon: Book,
			items: [
				'Agentes Aduanales',
				'Clases',
				'Partes',
				'Clientes Proveedores',
				'Fracciones Americanas y de Canada',
				'Pedimentos',
				'Partidas',
				'Tipos de Cambio',
				'Transportistas',
				'Unidades de Medida',
				'Interfaz Impo-Expo',
				'Carta Porte',
				'Listado de Entradas'
			]
		},
		{ label: 'Búsquedas', icon: Search, items: [] },
		{ label: 'Localizaciones', icon: MapPin, items: [] },
		{
			label: 'Declaraciones',
			icon: FileText,
			items: ['Hoja de Cálculo', 'Manifestación al Valor', 'Importación vs Exportación']
		},
		{
			label: 'Generales',
			icon: Settings,
			items: ['Verificación de Pedimento', 'Reporte de Pedimentos por A. Aduanal']
		},
		{
			label: 'EXCEL',
			icon: FileSpreadsheet,
			items: ['Depreciación de Activo Fijo']
		},
		{
			label: 'Movimientos',
			icon: ArrowLeftRight,
			items: ['Facturas Impo/Expo', 'Partidas Impo/Expo', 'Reporte de lotes']
		},
		{ label: 'Auditorias', icon: ShieldCheck, items: ['SCAF vs Almacén'] }
	];

	let dates = $state({
		from: '',
		to: '',
		type: 'invoice' as 'invoice' | 'payment'
	});

	let types = $state({
		import: { DEF: false, TEM: false, REP: false },
		export: {
			// Tipo Principal (ahora checkboxes)
			main: { DEF: false, CREG: false, REP: false },
			// Opciones adicionales (Checkboxes)
			additional: {
				AFIJO: false,
				REEXP: false,
				NODES: false,
				DONAC: false,
				SCRAP: false,
				TODAS: false
			}
		},
		other: { VEMEX: false, CREGEXP: false, COMEX: false, TODAS: false }
	});

	let filters = $state({
		includeNA: false,
		downloaded: 'all' as 'all' | 'downloaded' | 'not_downloaded'
	});

	let selectors = $state({
		provider: '',
		soldTo: '',
		pedimentoKey: ''
	});

	let config = $state({
		currency: 'capture' as 'foreign' | 'national' | 'capture',
		reportType: 'normal' as 'normal' | 'detailed',
		exchangeRate: 'invoice_date' as 'invoice_date' | 'payment_date',
		sendEmail: false,
		julianDate: false,
		shelter: false
	});

	let loading = $state(false);
	let results = $state<MovementItem[] | MovementItemDetailed[]>([]);
	let showResults = $state(false);
	let reportTitle = $state('REPORTE DE FACTURAS');
	let currencyLabel = $state('Moneda: Pesos');

	// Diálogo de selección
	let dialogOpen = $state(false);
	let dialogType: 'provider' | 'soldTo' | 'pedimentoKey' | null = $state(null);
	let clientsProviders = $state<any[]>([]);
	let pedimentoCodes = $state<any[]>([]);
	let dialogSearch = $state('');

	function handleTodasChange(checked: boolean) {
		if (checked) {
			// Clarion: IF Loc:Todas = 1 THEN ...
			// Solo marca los checkboxes específicos que marca Clarion

			// Importación: Definitiva, Temporal, Reparación
			types.import.DEF = true; // Loc:ImpoDef = 1
			types.import.TEM = true; // Loc:ImpoTemp = 1
			types.import.REP = true; // Loc:ImpoRep = 1

			// Exportación Principal: Solo Cambio de Régimen
			types.export.main.CREG = true; // Loc:CamRegimen = 1
			// NO marca DEF ni REP según el código Clarion

			// Exportación Adicional: Todas las opciones
			types.export.additional.AFIJO = true; // Loc:ExpoAFijo = 1
			types.export.additional.REEXP = true; // Loc:ExpoReExp = 1
			types.export.additional.NODES = true; // Loc:ExpoNodes = 1
			types.export.additional.DONAC = true; // Loc:ExpoDonac = 1
			types.export.additional.SCRAP = true; // Loc:ExpoScrap = 1

			// Otras: VeMex y ComMex
			types.other.VEMEX = true; // Loc:VeMex = 1
			types.other.COMEX = true; // Loc:ComMex = 1
			// NO marca CREGEXP según el código Clarion
		} else {
			// Clarion: ELSE ... = 0
			// Desmarcar los mismos checkboxes
			types.import.DEF = false;
			types.import.TEM = false;
			types.import.REP = false;

			types.export.main.CREG = false;

			types.export.additional.AFIJO = false;
			types.export.additional.REEXP = false;
			types.export.additional.NODES = false;
			types.export.additional.DONAC = false;
			types.export.additional.SCRAP = false;

			types.other.VEMEX = false;
			types.other.COMEX = false;
		}
	}

	// --- DERIVED STATE FOR EXPORT VALIDATION ---

	/**
	 * Determine which export additional options should be disabled based on main export type selection.
	 * Rules:
	 * - If REP (Reparación) is selected: disable REEXP, DONAC, SCRAP
	 * - If CREG (C. Régimen) is selected: disable REEXP, DONAC, NODES
	 */
	const isExportAdditionalDisabled = $derived({
		REEXP: types.export.main.REP || types.export.main.CREG,
		DONAC: types.export.main.REP || types.export.main.CREG,
		SCRAP: types.export.main.REP,
		NODES: types.export.main.CREG,
		AFIJO: false,
		TODAS: false
	});

	// Auto-uncheck disabled export additional options
	$effect(() => {
		if (isExportAdditionalDisabled.REEXP && types.export.additional.REEXP) {
			types.export.additional.REEXP = false;
		}
		if (isExportAdditionalDisabled.DONAC && types.export.additional.DONAC) {
			types.export.additional.DONAC = false;
		}
		if (isExportAdditionalDisabled.SCRAP && types.export.additional.SCRAP) {
			types.export.additional.SCRAP = false;
		}
		if (isExportAdditionalDisabled.NODES && types.export.additional.NODES) {
			types.export.additional.NODES = false;
		}
	});

	// --- VALIDACIONES ---

	function formatDateToYYYYMMDD(dateStr: string): string {
		if (!dateStr) return '';
		// dateStr viene como YYYY-MM-DD del input type="date"
		return dateStr.replace(/-/g, '');
	}

	function validateDates(): { valid: boolean; message?: string } {
		if (!dates.from || !dates.to) {
			return { valid: false, message: 'El rango de fechas es obligatorio' };
		}

		const fromDate = new Date(dates.from);
		const toDate = new Date(dates.to);

		if (fromDate > toDate) {
			return { valid: false, message: 'La fecha inicial no puede ser mayor que la fecha final' };
		}

		// Validar que no sea más de 1 año de diferencia
		const oneYearMs = 365 * 24 * 60 * 60 * 1000;
		if (toDate.getTime() - fromDate.getTime() > oneYearMs) {
			return { valid: false, message: 'El rango de fechas no puede ser mayor a 1 año' };
		}

		return { valid: true };
	}

	function validateMovementTypes(): { valid: boolean; message?: string } {
		const hasImportSelected = Object.values(types.import).some((v) => v);
		const hasOtherSelected = Object.values(types.other).some((v) => v);
		const hasExportAdditional = Object.values(types.export.additional).some((v) => v);
		const hasExportMain = Object.values(types.export.main).some((v) => v);

		if (!hasImportSelected && !hasOtherSelected && !hasExportAdditional && !hasExportMain) {
			return { valid: false, message: 'Debe seleccionar al menos un tipo de movimiento' };
		}

		return { valid: true };
	}

	function validateBusinessRules(): { valid: boolean; message?: string } {
		// Validación: Filtro de descargadas solo para Reparaciones y Exportaciones
		if (filters.downloaded !== 'all') {
			const hasRepairOrExport =
				types.import.REP ||
				Object.values(types.export.main).some((v) => v) ||
				Object.values(types.export.additional).some((v) => v);

			if (!hasRepairOrExport) {
				return {
					valid: false,
					message: 'El filtro de descargadas solo aplica a Reparaciones y Exportaciones'
				};
			}
		}

		// Si TODAS está marcado, saltar validaciones de combinaciones incompatibles
		// ya que es una combinación especial permitida en Clarion
		if (types.other.TODAS || types.export.additional.TODAS) {
			return { valid: true };
		}

		// Validación 3: COMEX y IMPDF son mutuamente excluyentes
		if (types.import.DEF && types.other.COMEX) {
			return {
				valid: false,
				message: 'No puede seleccionar IMPDF (Definitiva) y COMEX al mismo tiempo'
			};
		}

		// Validación 4: Para Exportaciones de Reparación (solo AFIJO y NODES)
		if (types.export.main.REP) {
			const invalidExportTypes =
				types.export.additional.SCRAP ||
				types.export.additional.REEXP ||
				types.export.additional.DONAC;

			if (invalidExportTypes) {
				return { valid: false, message: 'Exportaciones de Reparación solo permiten AFIJO y NODES' };
			}
		}

		// Validación 5: Para Cambio de Régimen (solo AFIJO o SCRAP)
		if (types.export.main.CREG) {
			const invalidCRegTypes =
				types.export.additional.NODES ||
				types.export.additional.REEXP ||
				types.export.additional.DONAC;

			if (invalidCRegTypes) {
				return { valid: false, message: 'Cambio de Régimen solo permite AFIJO o SCRAP' };
			}

			// No puede combinarse con otros tipos principales
			if (types.export.main.DEF || types.export.main.REP) {
				return {
					valid: false,
					message:
						'Cambio de Régimen no puede combinarse con otros tipos de exportación principales'
				};
			}
		}

		// Validación 6: VEMEX no puede combinarse con otros tipos de export
		if (types.other.VEMEX) {
			const hasOtherExports =
				types.export.additional.AFIJO ||
				types.export.additional.NODES ||
				types.export.additional.SCRAP ||
				types.export.additional.REEXP ||
				types.export.additional.DONAC ||
				Object.values(types.export.main).some((v) => v);

			if (hasOtherExports) {
				return {
					valid: false,
					message: 'VEMEX no puede combinarse con otros tipos de exportación'
				};
			}
		}

		// Validación 7: CREGEXP (Cambio Régimen Export) validaciones
		if (types.other.CREGEXP) {
			const hasOtherTypes =
				types.import.DEF ||
				types.import.TEM ||
				types.import.REP ||
				Object.values(types.export.main).some((v) => v) ||
				Object.values(types.export.additional).some((v) => v) ||
				types.other.VEMEX ||
				types.other.COMEX;

			if (hasOtherTypes) {
				return {
					valid: false,
					message: 'Cambio Régimen Export no puede combinarse con otros tipos'
				};
			}
		}

		// Validación 8: Tipo de fecha debe ser FF o FP
		if (dates.type !== 'invoice' && dates.type !== 'payment') {
			return { valid: false, message: 'Tipo de fecha debe ser Factura (FF) o Pago (FP)' };
		}

		return { valid: true };
	}

	// --- LÓGICA ---

	// Estado del Context Menu
	let contextMenu = $state({
		open: false,
		x: 0,
		y: 0
	});

	function handleContextMenu(e: MouseEvent) {
		e.preventDefault();
		contextMenu = {
			open: true,
			x: e.clientX,
			y: e.clientY
		};
	}

	function closeContextMenu() {
		contextMenu.open = false;
	}

	// Acción: Generar Reporte (Email / Background) - Click Izquierdo
	async function generateReport() {
		const filter = buildAllMovementsFilter();
		if (!filter) return;

		// Email sending is controlled by config.sendEmail checkbox

		loading = true;
		// Initial toast
		const toastId = toast.loading('Iniciando generación de reporte...');

		try {
			// 1. Trigger Async Generation
			const response = await invoiceMovementsApi.generateReportAsync(filter);

			if (!response.data || !response.data.task_id) {
				toast.error('Error al iniciar la generación del reporte', { id: toastId });
				loading = false;
				return;
			}

			const taskId = response.data.task_id;

			// 2. Poll for status
			const pollInterval = setInterval(async () => {
				try {
					const statusResponse = await invoiceMovementsApi.getTaskStatus(taskId);
					const statusData = statusResponse.data;

					if (!statusData) return;

					if (statusData.status === 'SUCCESS') {
						clearInterval(pollInterval);
						loading = false;

						// Download the file automatically
						if (statusData.result?.content) {
							try {
								// Decode base64 content
								const base64Content = statusData.result.content;
								const binaryString = atob(base64Content);
								const bytes = new Uint8Array(binaryString.length);
								for (let i = 0; i < binaryString.length; i++) {
									bytes[i] = binaryString.charCodeAt(i);
								}

								// Create blob and download
								const blob = new Blob([bytes], { type: 'text/csv;charset=utf-8;' });
								const url = window.URL.createObjectURL(blob);
								const link = document.createElement('a');
								link.href = url;
								link.download = statusData.result.file_name || 'reporte_facturas.csv';
								document.body.appendChild(link);
								link.click();
								document.body.removeChild(link);
								window.URL.revokeObjectURL(url);

								toast.success(
									`Reporte generado y descargado.${config.sendEmail ? ' También se ha enviado por correo.' : ''}`,
									{
										id: toastId
									}
								);
							} catch (downloadErr) {
								console.error('Error downloading file:', downloadErr);
								toast.success(
									`Reporte generado correctamente.${config.sendEmail ? ' Se ha enviado un correo con los resultados.' : ''}`,
									{ id: toastId }
								);
							}
						} else {
							toast.success(
								`Reporte generado correctamente.${config.sendEmail ? ' Se ha enviado un correo con los resultados.' : ''}`,
								{ id: toastId }
							);
						}
					} else if (statusData.status === 'FAILURE') {
						clearInterval(pollInterval);
						loading = false;
						// Try to extract specific error from meta or result
						const errorMsg =
							statusData.meta?.exc_message ||
							statusData.result?.exc_message ||
							statusData.result?.detail ||
							'Error en la generación del reporte';

						console.error('Task Failure Details:', statusData);
						toast.error(errorMsg, { id: toastId });
					} else if (statusData.status === 'PROCESSING') {
						// Update progress
						if (statusData.meta) {
							const { current, total, status } = statusData.meta;
							const percentage = Math.round((current / total) * 100);
							toast.loading(`${status} (${percentage}%)`, { id: toastId });
						}
					}
				} catch (err) {
					console.error('Error polling status:', err);
					// Don't stop polling on transient network errors, but maybe log it
				}
			}, 1000); // Poll every 1 second
		} catch (error: any) {
			console.error('Error generando reporte:', error);
			toast.error(error.message || 'Error al generar el reporte', { id: toastId });
			loading = false;
		}
	}

	// Acción: Vista Previa (Tabla) - Click Derecho -> Opción
	async function previewReport() {
		closeContextMenu();
		const filter = buildAllMovementsFilter();
		if (!filter) return;

		// Para preview, no enviamos correo (o respetamos config, pero generalmente preview es solo ver)
		filter.send_email = false;

		loading = true;
		results = [];
		showResults = false;

		toast.info('Cargando vista previa...');

		try {
			const response = await invoiceMovementsApi.getAllMovements(filter);

			if (response.error) {
				toast.error(response.error);
				return;
			}

			if (response.data) {
				results = response.data;
				showResults = true;

				if (results.length === 0) {
					toast.warning('No se encontraron resultados con los filtros seleccionados');
				} else {
					toast.success(`${results.length} registros cargados en vista previa`);
				}
			}
		} catch (error: any) {
			console.error('Error generando vista previa:', error);
			toast.error(error.message || 'Error al generar la vista previa');
		} finally {
			loading = false;
		}
	}

	// Helper para construir el filtro (extraído de la lógica anterior)
	function buildAllMovementsFilter(): AllMovementsFilter | null {
		// Validaciones
		const dateValidation = validateDates();
		if (!dateValidation.valid) {
			toast.error(`Error: ${dateValidation.message}`);
			return null;
		}
		const movementValidation = validateMovementTypes();
		if (!movementValidation.valid) {
			toast.error(`Error: ${movementValidation.message}`);
			return null;
		}
		const businessValidation = validateBusinessRules();
		if (!businessValidation.valid) {
			toast.error(`Error: ${businessValidation.message}`);
			return null;
		}

		const allMovementsFilter: AllMovementsFilter = {
			range_type: dates.type === 'invoice' ? 'FF' : 'FP',
			start_date: formatDateToYYYYMMDD(dates.from),
			end_date: formatDateToYYYYMMDD(dates.to),
			include_cancelled: filters.includeNA,
			provider: selectors.provider || null,
			buyer: selectors.soldTo || null,
			pedimento_code: selectors.pedimentoKey || null,
			report_type: config.reportType === 'normal' ? 'Normal' : 'Detallado',
			currency_type: config.currency === 'foreign' ? 'ME' : 'MN',
			exchange_rate_type: config.exchangeRate === 'invoice_date' ? 'FF' : 'FP',
			is_shelter: config.shelter,
			// Granular flags
			import_temp: !!types.import.TEM,
			import_def: !!types.import.DEF,
			import_rep: !!types.import.REP,
			export_def: !!(
				types.export.main.DEF ||
				types.other.VEMEX ||
				types.export.additional.TODAS ||
				Object.values(types.export.additional).some((v) => v)
			),
			export_rep: !!types.export.main.REP,
			send_email: config.sendEmail
		};

		// Override flags if "TODAS" is selected
		if (types.other.TODAS) {
			allMovementsFilter.import_temp = true;
			allMovementsFilter.import_def = true;
			allMovementsFilter.import_rep = true;
			allMovementsFilter.export_def = true;
			allMovementsFilter.export_rep = true;
			allMovementsFilter.operation_type = null;
		} else if (types.export.additional.TODAS) {
			// TODAS for exports: only search export movements
			allMovementsFilter.import_temp = false;
			allMovementsFilter.import_def = false;
			allMovementsFilter.import_rep = false;
			allMovementsFilter.export_def = true;
			allMovementsFilter.export_rep = true;
			allMovementsFilter.operation_type = 'exp';
		} else {
			const hasImports =
				allMovementsFilter.import_temp ||
				allMovementsFilter.import_def ||
				allMovementsFilter.import_rep;
			const hasExports = allMovementsFilter.export_def || allMovementsFilter.export_rep;

			if (hasImports && hasExports) {
				allMovementsFilter.operation_type = null;
			} else if (hasImports) {
				allMovementsFilter.operation_type = 'imp';
			} else if (hasExports) {
				allMovementsFilter.operation_type = 'exp';
			}
		}

		// Set discharge filter (Global)
		const dischargeFilter =
			filters.downloaded === 'downloaded'
				? 'SiDes'
				: filters.downloaded === 'not_downloaded'
					? 'NoDes'
					: 'ALL';
		allMovementsFilter.discharge_filter = dischargeFilter;

		return allMovementsFilter;
	}

	async function handleGenerateReport() {
		// Wrapper for compatibility if button still calls this
		await generateReport();
	}

	function downloadCSV() {
		if (results.length === 0) {
			toast.error('No hay resultados para exportar');
			return;
		}

		const lines: string[] = [];

		// Título del reporte
		lines.push(reportTitle);
		lines.push(''); // Línea vacía

		// Información de moneda
		lines.push(currencyLabel);
		lines.push(''); // Línea vacía

		// Total de registros
		lines.push(`TOTAL DE REGISTROS:,${results.length}`);
		lines.push(''); // Línea vacía

		if (config.reportType === 'normal') {
			// Headers modo NORMAL (22 columnas)
			const headers = [
				'PEDIMENTO',
				'PEDIMENTO18',
				'CLAVE',
				'PEDIMENTO R1',
				'FACTURA',
				'FECHA FACT',
				'VALOR TOTAL',
				'TIPO DE CAMBIO',
				'TIPO OPER.',
				'TIPO EXPO.',
				'CAMBIO REG.',
				'ESTATUS',
				'E-DOCUMENT',
				'NUM. OPERACION',
				'NÚMERO GAFETE ÚNICO',
				'ADUANA CRUCE',
				'PROYECTO',
				'USUARIO QUE CAPTURÓ LA FACTURA',
				'USUARIO QUE ACTUALIZÓ LA FACTURA',
				'FECHA PAGO',
				'NUM. CAJA',
				'SECUENCIA'
			];
			lines.push(headers.join(','));
			lines.push(''); // Línea vacía

			// Datos modo normal
			results.forEach((row) => {
				const values = [
					row.Pedimento || '',
					row.Pedimento18 || '',
					row.ClavePed || '',
					row.PedimentoR1 || '',
					`"${row.Factura}"`,
					config.julianDate ? row.FechaFactura || '' : formatDateFromYYYYMMDD(row.FechaFactura),
					row.ValorComercialMN || '0',
					row.TipoCambio || '0',
					row.TipoMovTemDef || '',
					row.TipoExpo || '',
					row.EsCambioRegimen || '',
					row.Estatus || '',
					row.EDocument || '',
					row.NumOperacionVU || '',
					row.NumGafUni || '',
					`"${row.AduanaCru || ''}"`,
					row.BaseDeDatos || '',
					row.UsuarioCap || '',
					row.UsuarioAcr || '',
					config.julianDate ? row.Fecha_Pago || '' : formatDateFromYYYYMMDD(row.Fecha_Pago),
					row.NumCaja || '',
					row.Lote || ''
				];
				lines.push(values.join(','));
			});
		} else {
			// Headers modo DETALLADO (47 columnas - más columnas que el normal)
			const headers = [
				'PEDIMENTO',
				'PEDIMENTO 18',
				'CLAVE',
				'REGIMEN',
				'PEDIMENTO R1',
				'FECHA INICIO',
				'FECHA FINAL',
				'FECHA PAGO',
				'REMESA',
				'FACTURA',
				'FECHA FACT',
				'FECHA EMISION',
				'PROVEEDOR',
				'RFC PROV.',
				'TAX ID PROV.',
				'CLIENTE',
				'RFC CLI.',
				'TAX ID CLI.',
				'AGENTE ADUANAL',
				'PATENTE',
				'ADUANA',
				'CLASE',
				'DESC ESPAÑOL',
				'DESC INGLES',
				'CANT. IMPO/EXPO',
				'U.M.',
				'VALOR COMERC',
				'TIPO DE CAMBIO',
				'PESO NETO',
				'PESO BRUTO',
				'ORDEN COMPRA/VENTA',
				'FRACCION ARANC.',
				'PREFERENCIA',
				'SECTOR',
				'PAIS ORIGEN',
				'TIPO OPER.',
				'TIPO EXPO.',
				'PARTIDA/SUBPARTIDA',
				'CAMBIO REG.',
				'ESTATUS',
				'E-DOCUMENT',
				'NUM. OPERACION',
				'MARCA',
				'MODELO',
				'SERIE(S)',
				'NÚMERO GAFETE ÚNICO',
				'FRACCION AMERICANA',
				'ECCN',
				'SIMBOLO DE LA EXCEPCION DE LICENCIA',
				'ADUANA CRUCE',
				'PROYECTO',
				'USUARIO QUE CAPTURÓ LA FACTURA',
				'USUARIO QUE ACTUALIZÓ LA FACTURA',
				'NUM CAJA',
				'TRANSPORTISTA',
				'LOTE',
				'LINEA PARTIDA'
			];
			lines.push(headers.join(','));
			lines.push(''); // Línea vacía

			// Datos modo detallado
			results.forEach((row: any) => {
				const values = [
					row.Pedimento || '',
					row.Pedimento18 || '',
					row.ClavePed || '',
					row.Regimen || '',
					row.PedimentoR1 || '',
					config.julianDate ? row.Fecha_Inicio || '' : formatDateFromYYYYMMDD(row.Fecha_Inicio),
					config.julianDate ? row.Fecha_Fin || '' : formatDateFromYYYYMMDD(row.Fecha_Fin),
					config.julianDate ? row.Fecha_Pago || '' : formatDateFromYYYYMMDD(row.Fecha_Pago),
					row.Remesa || '',
					`"${row.Factura}"`,
					config.julianDate ? row.FechaFactura || '' : formatDateFromYYYYMMDD(row.FechaFactura),
					config.julianDate ? row.FechaEmision || '' : formatDateFromYYYYMMDD(row.FechaEmision),
					row.Proveedor || '',
					row.RFCProveedor || '',
					row.ProveedorTaxID || '',
					row.VendidoA || '',
					row.VendidoARFC || '',
					row.VendidoATaxID || '',
					row.AgenteAduanal || '',
					row.Patente || '',
					row.Aduana || '',
					row.NumParte || '',
					row.DescripcionE || '',
					row.DescripcionI || '',
					row.CantidadIE || '0',
					row.UniMed || '',
					row.ValorComercialMN || '0',
					row.TipoCambio || '0',
					row.PesoNeto || '0',
					row.PesoBruto || '0',
					row.OrdenCompraVenta || '',
					row.FraccionArancelaria || '',
					row.Preferencia || '',
					row.Sector || '',
					row.PaisOrigen || '',
					row.TipoMovTemDef || '',
					row.TipoExpo || '',
					row.Advalorem || '',
					row.EsCambioRegimen || '',
					row.Estatus || '',
					row.EDocument || '',
					row.NumOperacionVU || '',
					row.Marca || '',
					row.Modelo || '',
					row.Series || '',
					row.NumGafUni || '',
					row.FraccionAmericana || '',
					row.ECCN || '',
					row.SimboloEx || '',
					`"${row.AduanaCru || ''}"`,
					row.BaseDeDatos || '',
					row.UsuarioCap || '',
					row.UsuarioAcr || '',
					row.NumCaja || '',
					row.Transportista || '',
					row.Lote || '',
					row.Linea || ''
				];
				lines.push(values.join(','));
			});
		}

		const csv = lines.join('\n');
		const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
		const url = URL.createObjectURL(blob);
		const link = document.createElement('a');
		link.href = url;
		const mode = config.reportType === 'normal' ? 'normal' : 'detallado';
		link.download = `reporte_facturas_${mode}_${formatDateToYYYYMMDD(dates.from)}_${formatDateToYYYYMMDD(dates.to)}.csv`;
		link.click();
		URL.revokeObjectURL(url);

		toast.success('Reporte descargado exitosamente');
	}

	function formatDateFromYYYYMMDD(dateStr: string | null): string {
		if (!dateStr || dateStr === '-' || dateStr === '0') return '-';

		// Si es un timestamp ISO (contiene 'T' o '-')
		if (dateStr.includes('T') || (dateStr.includes('-') && dateStr.length > 8)) {
			try {
				const date = new Date(dateStr);
				// Verificar si es una fecha válida
				if (isNaN(date.getTime())) return '-';
				// Si es 1970 o anterior, es una fecha inválida/vacía
				if (date.getFullYear() <= 1970) return '-';

				const day = String(date.getDate()).padStart(2, '0');
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const year = date.getFullYear();
				return `${day}/${month}/${year}`;
			} catch {
				return '-';
			}
		}

		// YYYYMMDD -> DD/MM/YYYY
		if (dateStr.length === 8 && /^\d{8}$/.test(dateStr)) {
			const year = dateStr.substring(0, 4);
			const month = dateStr.substring(4, 6);
			const day = dateStr.substring(6, 8);
			return `${day}/${month}/${year}`;
		}

		return dateStr;
	}

	function formatCurrency(value: number | null | undefined): string {
		if (value === null || value === undefined) return '-';
		return new Intl.NumberFormat('en-US', {
			minimumFractionDigits: 2,
			maximumFractionDigits: 2
		}).format(value);
	}

	function handleClose() {
		// Reset form instead of navigating back
		showResults = false;
		results = [];
		loading = false;
	}

	async function openSelectionDialog(type: 'provider' | 'soldTo' | 'pedimentoKey') {
		dialogType = type;
		dialogSearch = '';

		if (type === 'pedimentoKey') {
			// Cargar claves de pedimento
			try {
				const response = await api.get(
					'/v1/public/refrence_data/pedimento-codes?page=1&page_size=100'
				);
				pedimentoCodes = response.data?.items || [];
				dialogOpen = true;
			} catch (error: any) {
				console.error('Error cargando claves de pedimento:', error);
				toast.error('Error al cargar las claves de pedimento');
			}
			return;
		}

		const companyId = companyStore.activeCompany?.id;
		if (!companyId) {
			toast.error('No hay compañía seleccionada');
			return;
		}
		let isLoadingDialog = true;
		try {
			// No filtramos por tipo en el API para obtener todos los registros
			// Filtraremos client-side para incluir 'both'
			const response = await api.get(
				`/v1/a76/clients-providers?company_id=${companyId}&limit=1000`
			);
			const allItems = response.data?.items || [];

			// Filtrar según el tipo solicitado, incluyendo 'both'
			const searchType = type === 'provider' ? 'provider' : 'client';
			clientsProviders = allItems.filter(
				(item: any) => item.client_or_provider === searchType || item.client_or_provider === 'both'
			);

			dialogOpen = true;
		} catch (error: any) {
			console.error('Error cargando datos:', error);
			toast.error('Error al cargar la lista');
		} finally {
			isLoadingDialog = false;
		}
	}

	function selectItem(item: any) {
		if (dialogType === 'provider') {
			selectors.provider = item.name || '';
		} else if (dialogType === 'soldTo') {
			selectors.soldTo = item.name || '';
		} else if (dialogType === 'pedimentoKey') {
			selectors.pedimentoKey = item.code || '';
		}
		dialogOpen = false;
	}

	const filteredItems = $derived(
		dialogType === 'pedimentoKey'
			? pedimentoCodes.filter((item) => {
					if (!dialogSearch) return true;
					const searchLower = dialogSearch.toLowerCase();
					return (
						item.code?.toLowerCase().includes(searchLower) ||
						item.description?.toLowerCase().includes(searchLower)
					);
				})
			: clientsProviders.filter((item) => {
					if (!dialogSearch) return true;
					const searchLower = dialogSearch.toLowerCase();
					return (
						item.name?.toLowerCase().includes(searchLower) ||
						item.rfc?.toLowerCase().includes(searchLower) ||
						item.tax_id?.toLowerCase().includes(searchLower)
					);
				})
	);
</script>

<div
	class="animate-in fade-in slide-in-from-bottom-4 flex h-[calc(100vh-3.5rem)] flex-col gap-1.5 overflow-hidden duration-500"
>
	<!-- Encabezado de Página Compacto -->
	<div class="flex shrink-0 items-center justify-between px-1">
		<div class="flex items-center gap-3">
			<h1 class="flex items-center gap-2 text-xl font-bold tracking-tight text-foreground">
				<FileSearch class="h-6 w-6 text-primary" />
				Reporte de Facturas
			</h1>
			<span
				class="rounded-full border bg-muted px-2 py-0.5 text-[10px] font-medium text-muted-foreground"
			>
				V2.0
			</span>
		</div>
		<div class="text-xs text-muted-foreground">Sistema Fiscal</div>
	</div>

	<Separator />

	<!-- Sección de Acceso Rápido (Gestión de Pedimentos) Compacta -->
	<div class="grid shrink-0 grid-cols-10 gap-2">
		{#each menuOptions as item}
			{#if item.items.length > 0}
				<DropdownMenu.Root>
					<DropdownMenu.Trigger class="w-full">
						{#snippet child({ props })}
							<Button
								{...props}
								variant="outline"
								size="sm"
								class="flex h-10 w-full items-center justify-center gap-2 border-dashed text-muted-foreground transition-all hover:border-solid hover:border-primary/50 hover:bg-primary/5 hover:text-primary"
							>
								<item.icon class="h-4 w-4" />
								<span class="hidden text-xs font-bold tracking-wider uppercase xl:inline-block"
									>{item.label}</span
								>
							</Button>
						{/snippet}
					</DropdownMenu.Trigger>
					<DropdownMenu.Content class="w-56">
						<DropdownMenu.Label
							class="text-xs font-bold tracking-wider text-muted-foreground uppercase"
							>{item.label}</DropdownMenu.Label
						>
						<DropdownMenu.Separator />
						<div class="max-h-[300px] overflow-y-auto">
							{#each item.items as subItem}
								<DropdownMenu.Item onclick={() => toast.info(`Seleccionado: ${subItem}`)}>
									{subItem}
								</DropdownMenu.Item>
							{/each}
						</div>
					</DropdownMenu.Content>
				</DropdownMenu.Root>
			{:else}
				<Button
					variant="outline"
					size="sm"
					class="flex h-10 w-full items-center justify-center gap-2 border-dashed text-muted-foreground transition-all hover:border-solid hover:border-primary/50 hover:bg-primary/5 hover:text-primary"
					onclick={() => toast.info(`Acción rápida: ${item.label}`)}
				>
					<item.icon class="h-4 w-4" />
					<span class="hidden text-xs font-bold tracking-wider uppercase xl:inline-block"
						>{item.label}</span
					>
				</Button>
			{/if}
		{/each}
	</div>

	<Separator />

	<!-- Contenido Principal - Layout Normal -->
	<div class="grid min-h-0 flex-1 grid-cols-3 content-start items-start gap-2">
		<!-- Columna 1: Fechas y Clasificación -->
		<Card.Root class="flex h-full flex-col">
			<Card.Header class="shrink-0 border-b bg-muted/20 px-3 py-2">
				<Card.Title class="flex items-center gap-2 text-sm font-semibold text-primary">
					<Calendar class="h-4 w-4" /> Periodo y Clasificación
				</Card.Title>
			</Card.Header>
			<Card.Content class="flex-1 space-y-3 p-3">
				<div class="flex items-center gap-3">
					<div class="flex-1 space-y-1">
						<Label class="text-xs font-bold text-muted-foreground uppercase">Fecha Inicio</Label>
						<Input
							type="date"
							class="h-8 cursor-pointer"
							bind:value={dates.from}
							onclick={(e) => {
								const input = e.currentTarget;
								if (input && typeof input.showPicker === 'function') {
									input.showPicker();
								}
							}}
						/>
					</div>
					<div class="flex-1 space-y-1">
						<Label class="text-xs font-bold text-muted-foreground uppercase">Fecha Fin</Label>
						<Input
							type="date"
							class="h-8 cursor-pointer"
							bind:value={dates.to}
							onclick={(e) => {
								const input = e.currentTarget;
								if (input && typeof input.showPicker === 'function') {
									input.showPicker();
								}
							}}
						/>
					</div>
				</div>

				<Separator />

				<div class="space-y-4">
					<!-- Importación -->
					<div>
						<Label
							class="mb-2 block border-b pb-1 text-xs font-bold text-muted-foreground uppercase"
							>Importación</Label
						>
						<div class="grid grid-cols-3 gap-2">
							{#each Object.keys(types.import) as key}
								<div class="flex items-center space-x-2">
									<Checkbox
										id="imp-{key}"
										class="h-3.5 w-3.5"
										disabled={types.other.TODAS}
										bind:checked={types.import[key as keyof typeof types.import]}
									/>
									<Label for="imp-{key}" class="cursor-pointer text-xs font-medium">
										{key === 'DEF' ? 'Definitiva' : key === 'TEM' ? 'Temporal' : 'Reparación'}
									</Label>
								</div>
							{/each}
						</div>
					</div>

					<!-- Exportación -->
					<div>
						<Label
							class="mb-2 block border-b pb-1 text-xs font-bold text-muted-foreground uppercase"
							>Exportación</Label
						>
						<div class="space-y-3">
							<!-- Main Types -->
							<div class="grid grid-cols-3 gap-2">
								<div class="flex items-center space-x-2">
									<Checkbox
										id="exp-m-def"
										class="h-3.5 w-3.5"
										disabled={types.other.TODAS}
										bind:checked={types.export.main.DEF}
									/>
									<Label for="exp-m-def" class="cursor-pointer text-xs font-medium"
										>Definitiva</Label
									>
								</div>
								<div class="flex items-center space-x-2">
									<Checkbox
										id="exp-m-creg"
										class="h-3.5 w-3.5"
										disabled={types.other.TODAS}
										bind:checked={types.export.main.CREG}
									/>
									<Label for="exp-m-creg" class="cursor-pointer text-xs font-medium"
										>C. Régimen</Label
									>
								</div>
								<div class="flex items-center space-x-2">
									<Checkbox
										id="exp-m-rep"
										class="h-3.5 w-3.5"
										disabled={types.other.TODAS}
										bind:checked={types.export.main.REP}
									/>
									<Label for="exp-m-rep" class="cursor-pointer text-xs font-medium"
										>Reparación</Label
									>
								</div>
							</div>

							<!-- Additional Options (Sin subtítulo) -->
							<div class="grid grid-cols-3 gap-2">
								{#each Object.keys(types.export.additional) as key}
									<div class="flex items-center space-x-2">
										<Checkbox
											id="exp-add-{key}"
											class="h-3.5 w-3.5"
											disabled={(types.other.TODAS && key !== 'TODAS') ||
												isExportAdditionalDisabled[key as keyof typeof isExportAdditionalDisabled]}
											bind:checked={
												types.export.additional[key as keyof typeof types.export.additional]
											}
										/>
										<Label for="exp-add-{key}" class="cursor-pointer text-[10px] font-normal"
											>{key}</Label
										>
									</div>
								{/each}
							</div>
						</div>
					</div>

					<!-- Otras -->
					<div>
						<Label
							class="mb-2 block border-b pb-1 text-xs font-bold text-muted-foreground uppercase"
							>Otras</Label
						>
						<div class="grid grid-cols-3 gap-2">
							{#each Object.keys(types.other) as key}
								<div class="flex items-center space-x-2">
									<Checkbox
										id="other-{key}"
										class="h-3.5 w-3.5"
										disabled={types.other.TODAS && key !== 'TODAS'}
										bind:checked={types.other[key as keyof typeof types.other]}
										onCheckedChange={(v) => {
											if (key === 'TODAS') handleTodasChange(v as boolean);
										}}
									/>
									<Label for="other-{key}" class="cursor-pointer text-xs font-normal">
										{key === 'CREGEXP' ? 'C. REG. EXP.' : key}
									</Label>
								</div>
							{/each}
						</div>
					</div>
				</div>
			</Card.Content>
		</Card.Root>

		<!-- Columna 2: Filtros e Identificadores -->
		<Card.Root class="flex h-full flex-col">
			<Card.Header class="shrink-0 border-b bg-muted/20 px-3 py-2">
				<Card.Title class="flex items-center gap-2 text-sm font-semibold text-primary">
					<Search class="h-4 w-4" /> Filtros e Identificadores
				</Card.Title>
			</Card.Header>
			<Card.Content class="flex-1 space-y-3 p-3">
				<div class="space-y-2">
					{#each [{ label: 'Proveedor', key: 'provider' as const }, { label: 'Vendido a', key: 'soldTo' as const }, { label: 'Clave de Pedimento', key: 'pedimentoKey' as const }] as item}
						<div class="space-y-1">
							<Label class="text-xs font-bold text-muted-foreground uppercase">{item.label}</Label>
							<div class="flex items-center gap-2">
								<Input
									bind:value={selectors[item.key]}
									class="h-8 flex-1 text-sm"
									placeholder={`Buscar ${item.label.split('/')[0]}...`}
								/>
								<Button
									variant="outline"
									size="icon"
									class="h-8 w-8 shrink-0"
									onclick={() => openSelectionDialog(item.key)}
								>
									<Folder class="h-4 w-4" />
								</Button>
							</div>
						</div>
					{/each}
				</div>

				<div class="py-1">
					<Separator />
				</div>

				<div class="space-y-2">
					<Label class="text-xs font-bold text-muted-foreground uppercase"
						>Filtros por Partida</Label
					>

					<div
						class="flex items-center space-x-2 rounded-md border bg-muted/10 p-2 transition-colors hover:bg-muted/20"
					>
						<Checkbox id="filter-na" class="h-4 w-4" bind:checked={filters.includeNA} />
						<Label for="filter-na" class="cursor-pointer text-sm font-medium"
							>Incluir Facturas NA</Label
						>
					</div>

					<div class="space-y-1.5 pt-1">
						<RadioGroup.Root bind:value={filters.downloaded} class="flex flex-col gap-1.5">
							<div
								class="flex items-center space-x-3 rounded-md border px-3 py-2 transition-colors hover:bg-muted/50"
							>
								<RadioGroup.Item value="all" id="d1" class="h-4 w-4" />
								<Label for="d1" class="flex-1 cursor-pointer text-sm font-medium"
									>Todas las Partidas</Label
								>
							</div>
							<div
								class="flex items-center space-x-3 rounded-md border px-3 py-2 transition-colors hover:bg-muted/50"
							>
								<RadioGroup.Item value="downloaded" id="d2" class="h-4 w-4" />
								<Label for="d2" class="flex-1 cursor-pointer text-sm font-medium"
									>Solo Descargadas</Label
								>
							</div>
							<div
								class="flex items-center space-x-3 rounded-md border px-3 py-2 transition-colors hover:bg-muted/50"
							>
								<RadioGroup.Item value="not_downloaded" id="d3" class="h-4 w-4" />
								<Label for="d3" class="flex-1 cursor-pointer text-sm font-medium"
									>Solo No Descargadas</Label
								>
							</div>
						</RadioGroup.Root>
					</div>
				</div>
			</Card.Content>
		</Card.Root>

		<!-- Columna 3: Configuración y Acciones -->
		<Card.Root class="flex h-full flex-col">
			<Card.Header class="shrink-0 border-b bg-muted/20 px-3 py-2">
				<Card.Title class="flex items-center gap-2 text-sm font-semibold text-primary">
					<Globe class="h-4 w-4" /> Configuración Final
				</Card.Title>
			</Card.Header>
			<Card.Content class="flex-1 space-y-4 p-3">
				<div class="grid grid-cols-2 gap-3">
					<div class="space-y-1.5">
						<Label class="text-xs font-bold text-muted-foreground uppercase">Tipo de Fecha</Label>
						<RadioGroup.Root bind:value={dates.type} class="flex flex-col gap-1">
							<div
								class="flex items-center space-x-2 rounded-md border px-2 py-1.5 transition-colors hover:bg-muted"
							>
								<RadioGroup.Item value="invoice" id="dt-inv" class="h-4 w-4" />
								<Label for="dt-inv" class="flex-1 cursor-pointer text-sm font-medium">Factura</Label
								>
							</div>
							<div
								class="flex items-center space-x-2 rounded-md border px-2 py-1.5 transition-colors hover:bg-muted"
							>
								<RadioGroup.Item value="payment" id="dt-pay" class="h-4 w-4" />
								<Label for="dt-pay" class="flex-1 cursor-pointer text-sm font-medium">Pago</Label>
							</div>
						</RadioGroup.Root>
					</div>

					<div class="space-y-1.5">
						<Label class="text-xs font-bold text-muted-foreground uppercase">Tipo de Moneda</Label>
						<RadioGroup.Root bind:value={config.currency} class="flex flex-col gap-1">
							<div
								class="flex items-center space-x-2 rounded-md border px-2 py-1.5 transition-colors hover:bg-muted"
							>
								<RadioGroup.Item value="foreign" id="curr-usd" class="h-4 w-4" />
								<Label for="curr-usd" class="flex-1 cursor-pointer text-sm font-medium"
									>Extranjera</Label
								>
							</div>
							<div
								class="flex items-center space-x-2 rounded-md border px-2 py-1.5 transition-colors hover:bg-muted"
							>
								<RadioGroup.Item value="national" id="curr-mxn" class="h-4 w-4" />
								<Label for="curr-mxn" class="flex-1 cursor-pointer text-sm font-medium"
									>Nacional</Label
								>
							</div>
							<div
								class="flex items-center space-x-2 rounded-md border px-2 py-1.5 transition-colors hover:bg-muted"
							>
								<RadioGroup.Item value="capture" id="curr-cap" class="h-4 w-4" />
								<Label for="curr-cap" class="flex-1 cursor-pointer text-sm font-medium"
									>Captura</Label
								>
							</div>
						</RadioGroup.Root>
					</div>
				</div>

				<div class="py-1">
					<Separator />
				</div>

				<div class="grid grid-cols-2 gap-3">
					<div class="space-y-1.5">
						<Label class="text-xs font-bold text-muted-foreground uppercase">Reporte</Label>
						<RadioGroup.Root bind:value={config.reportType} class="flex flex-col gap-1.5">
							<div class="flex items-center space-x-2">
								<RadioGroup.Item value="normal" id="rt-norm" class="h-4 w-4" />
								<Label for="rt-norm" class="cursor-pointer text-sm font-medium">Normal</Label>
							</div>
							<div class="flex items-center space-x-2">
								<RadioGroup.Item value="detailed" id="rt-det" class="h-4 w-4" />
								<Label for="rt-det" class="cursor-pointer text-sm font-medium">Detallado</Label>
							</div>
						</RadioGroup.Root>
					</div>
					<div class="space-y-1.5">
						<Label class="text-xs font-bold text-muted-foreground uppercase">Tipo de Cambio</Label>
						<RadioGroup.Root bind:value={config.exchangeRate} class="flex flex-col gap-1.5">
							<div class="flex items-center space-x-2">
								<RadioGroup.Item value="invoice_date" id="er-inv" class="h-4 w-4" />
								<Label for="er-inv" class="cursor-pointer text-sm font-medium">Fecha Factura</Label>
							</div>
							<div class="flex items-center space-x-2">
								<RadioGroup.Item value="payment_date" id="er-pay" class="h-4 w-4" />
								<Label for="er-pay" class="cursor-pointer text-sm font-medium">Fecha Pago</Label>
							</div>
						</RadioGroup.Root>
					</div>
				</div>

				<div class="space-y-2 border-t pt-1">
					<Label class="text-xs font-bold text-muted-foreground uppercase">Opciones Avanzadas</Label
					>
					<div class="flex flex-col gap-1.5">
						<div
							class="flex items-center justify-between rounded border p-2 transition-colors hover:bg-muted/10"
						>
							<Label for="opt-email" class="cursor-pointer text-sm"
								>Enviar por Correo Electrónico</Label
							>
							<Checkbox id="opt-email" class="h-4 w-4" bind:checked={config.sendEmail} />
						</div>
						<div
							class="flex items-center justify-between rounded border p-2 transition-colors hover:bg-muted/10"
						>
							<Label for="opt-julian" class="flex-1 cursor-pointer text-sm"
								>Usar Fecha Juliana (Excel)</Label
							>
							<Checkbox id="opt-julian" class="h-4 w-4" bind:checked={config.julianDate} />
						</div>
						<div
							class="flex items-center justify-between rounded border p-2 transition-colors hover:bg-muted/10"
						>
							<Label for="opt-shelter" class="flex-1 cursor-pointer text-sm"
								>Generar Reporte Shelter</Label
							>
							<Checkbox id="opt-shelter" class="h-4 w-4" bind:checked={config.shelter} />
						</div>
					</div>
				</div>
			</Card.Content>
			<Card.Footer class="mt-auto gap-2 border-t bg-muted/10 p-2.5">
				<Button
					class="h-9 flex-1 text-sm shadow-sm"
					size="default"
					onclick={generateReport}
					oncontextmenu={handleContextMenu}
					disabled={loading}
				>
					{#if loading}
						<div
							class="mr-2 h-3.5 w-3.5 animate-spin rounded-full border-2 border-primary-foreground/30 border-t-primary-foreground"
						></div>
						Generando...
					{:else}
						<Printer class="mr-2 h-3.5 w-3.5" />
						Imprimir Reporte
					{/if}
				</Button>
				<Button
					variant="ghost"
					size="icon"
					class="h-9 w-9 text-muted-foreground hover:text-destructive"
					onclick={handleClose}
				>
					<X class="h-4 w-4" />
				</Button>
			</Card.Footer>
		</Card.Root>
	</div>

	<!-- Tabla de Resultados (Dialog Modal) -->
	<Dialog.Root
		open={showResults}
		onOpenChange={(v) => {
			if (!v) showResults = false;
		}}
	>
		<Dialog.Content showCloseButton={false} class="flex h-[90vh] !max-w-[95vw] flex-col gap-0 p-0">
			<Dialog.Header class="shrink-0 border-b bg-muted/40 px-6 py-4">
				<div class="flex items-center justify-between">
					<div>
						<Dialog.Title class="flex items-center gap-2 text-xl">
							<FileText class="h-5 w-5 text-primary" />
							{reportTitle}
						</Dialog.Title>
						<Dialog.Description class="mt-1.5">
							{results.length} registros encontrados • {currencyLabel}
						</Dialog.Description>
					</div>
					<div class="flex gap-2">
						<Button variant="outline" size="sm" onclick={downloadCSV} class="gap-2 shadow-sm">
							<Download class="h-4 w-4" />
							Exportar CSV
						</Button>
						<Dialog.Close
							class="inline-flex h-9 w-9 items-center justify-center rounded-md border border-input bg-background whitespace-nowrap shadow-sm ring-offset-background transition-colors hover:bg-accent hover:bg-muted hover:text-accent-foreground hover:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:outline-none disabled:pointer-events-none disabled:opacity-50"
						>
							<X class="h-4 w-4" />
							<span class="sr-only">Cerrar</span>
						</Dialog.Close>
					</div>
				</div>
			</Dialog.Header>

			<div class="flex-1 overflow-auto bg-muted/20 p-4">
				<div class="overflow-hidden rounded-md border bg-card text-card-foreground shadow-sm">
					<table class="w-full border-collapse text-left text-sm">
						<thead
							class="sticky top-0 z-10 border-b border-border bg-muted/80 text-muted-foreground shadow-sm backdrop-blur-sm"
						>
							<tr>
								{#each config.reportType === 'normal' ? ['PEDIMENTO', 'CLAVE', 'FACTURA', 'FECHA FACT', 'VALOR COM.', 'TIPO OPER.', 'ESTATUS', 'PROYECTO'] : ['PEDIMENTO', 'FACTURA', 'FECHA FACT', 'PROVEEDOR', 'CLIENTE', 'CANTIDAD', 'DESC. ESPAÑOL', 'TIPO OPER.'] as header}
									<th
										class="px-4 py-3 text-xs font-semibold tracking-wider whitespace-nowrap uppercase"
									>
										{header}
									</th>
								{/each}
							</tr>
						</thead>
						<tbody class="divide-y divide-border">
							{#each results as row}
								<tr class="bg-card transition-colors hover:bg-muted/50">
									{#if config.reportType === 'normal'}
										<td
											class="border-r-dashed border-r border-border/50 px-4 py-2.5 font-medium text-primary"
											>{row.Pedimento || '-'}</td
										>
										<td class="border-r-dashed border-r border-border/50 px-4 py-2.5"
											>{row.ClavePed || '-'}</td
										>
										<td
											class="border-r-dashed border-r border-border/50 px-4 py-2.5 font-mono whitespace-nowrap"
											>{row.Factura}</td
										>
										<td
											class="border-r-dashed border-r border-border/50 px-4 py-2.5 text-xs text-muted-foreground"
											>{formatDateFromYYYYMMDD(row.FechaFactura)}</td
										>
										<td
											class="border-r-dashed border-r border-border/50 px-4 py-2.5 text-right font-mono"
											>${formatCurrency(row.ValorComercialMN)}</td
										>
										<td class="border-r-dashed border-r border-border/50 px-4 py-2.5">
											<span
												class="rounded-full border border-blue-200 bg-blue-100 px-2 py-0.5 text-[10px] font-bold text-blue-700 dark:border-blue-800 dark:bg-blue-900/30 dark:text-blue-400"
											>
												{row.TipoMovTemDef}
											</span>
										</td>
										<td class="border-r-dashed border-r border-border/50 px-4 py-2.5">
											<span
												class="rounded-full px-2 py-0.5 text-[10px] font-bold {row.Estatus === 'C'
													? 'border border-destructive/20 bg-destructive/10 text-destructive'
													: 'border border-green-200 bg-green-100 text-green-700 dark:border-green-800 dark:bg-green-900/30 dark:text-green-400'}"
											>
												{row.Estatus || 'A'}
											</span>
										</td>
										<td class="px-4 py-2.5 text-xs text-muted-foreground">{row.BaseDeDatos}</td>
									{:else}
										{@const detailRow = row as MovementItemDetailed}
										<td
											class="border-r-dashed border-r border-border/50 px-4 py-2.5 font-medium text-primary"
											>{detailRow.Pedimento || '-'}</td
										>
										<td
											class="border-r-dashed border-r border-border/50 px-4 py-2.5 font-mono font-medium whitespace-nowrap"
											>{detailRow.Factura}</td
										>
										<td
											class="border-r-dashed border-r border-border/50 px-4 py-2.5 text-xs text-muted-foreground"
											>{formatDateFromYYYYMMDD(detailRow.FechaFactura)}</td
										>
										<td
											class="border-r-dashed max-w-[150px] truncate border-r border-border/50 px-4 py-2.5 text-xs"
											title={detailRow.Proveedor}>{detailRow.Proveedor || '-'}</td
										>
										<td
											class="border-r-dashed max-w-[150px] truncate border-r border-border/50 px-4 py-2.5 text-xs"
											title={detailRow.VendidoA}>{detailRow.VendidoA || '-'}</td
										>
										<td
											class="border-r-dashed border-r border-border/50 px-4 py-2.5 text-right font-mono"
											>{detailRow.CantidadIE || '0'}</td
										>
										<td
											class="border-r-dashed max-w-[200px] truncate border-r border-border/50 px-4 py-2.5 text-xs"
											title={detailRow.DescripcionE}>{detailRow.DescripcionE || '-'}</td
										>
										<td class="px-4 py-2.5">
											<span
												class="rounded-full border border-purple-200 bg-purple-100 px-2 py-0.5 text-[10px] font-bold text-purple-700 dark:border-purple-800 dark:bg-purple-900/30 dark:text-purple-400"
											>
												{detailRow.TipoMovTemDef}
											</span>
										</td>
									{/if}
								</tr>
							{/each}
						</tbody>
					</table>
				</div>
			</div>
		</Dialog.Content>
	</Dialog.Root>
</div>

<!-- Diálogo de Selección -->
<Dialog.Root bind:open={dialogOpen}>
	<Dialog.Content class="!max-w-[90vw] p-6 sm:!max-w-[90vw]">
		<Dialog.Header>
			<Dialog.Title>
				Seleccionar {dialogType === 'pedimentoKey'
					? 'Clave de Pedimento'
					: dialogType === 'provider'
						? 'Proveedor'
						: 'Cliente'}
			</Dialog.Title>
			<Dialog.Description>
				Busca y selecciona {dialogType === 'pedimentoKey'
					? 'una clave de pedimento'
					: dialogType === 'provider'
						? 'un proveedor'
						: 'un cliente'} de la lista
			</Dialog.Description>
		</Dialog.Header>

		<div class="mt-4">
			<div class="mb-3 flex items-center gap-2">
				<Search class="h-4 w-4 text-muted-foreground" />
				<Input
					bind:value={dialogSearch}
					placeholder={dialogType === 'pedimentoKey'
						? 'Buscar por código o descripción...'
						: 'Buscar por nombre, RFC, calle, ciudad...'}
					class="flex-1"
				/>
			</div>

			<div class="max-h-[55vh] overflow-x-auto rounded-lg border">
				{#if dialogType === 'pedimentoKey'}
					<table class="w-full text-sm">
						<thead class="bg-muted">
							<tr>
								<th
									class="sticky top-0 bg-muted px-3 py-2 text-left font-semibold whitespace-nowrap"
									>Código</th
								>
								<th
									class="sticky top-0 bg-muted px-3 py-2 text-left font-semibold whitespace-nowrap"
									>Descripción</th
								>
								<th
									class="sticky top-0 bg-muted px-3 py-2 text-center font-semibold whitespace-nowrap"
									>Acción</th
								>
							</tr>
						</thead>
						<tbody>
							{#if filteredItems.length === 0}
								<tr>
									<td colspan="3" class="px-4 py-8 text-center text-muted-foreground">
										No se encontraron resultados
									</td>
								</tr>
							{:else}
								{#each filteredItems as item}
									<tr
										class="cursor-pointer border-b transition-colors hover:bg-muted/50"
										onclick={() => selectItem(item)}
									>
										<td class="px-3 py-2.5 font-medium">{item.code || '-'}</td>
										<td class="px-3 py-2.5">{item.description || '-'}</td>
										<td class="px-3 py-2.5 text-center">
											<Button size="sm" variant="ghost" class="h-8">Seleccionar</Button>
										</td>
									</tr>
								{/each}
							{/if}
						</tbody>
					</table>
				{:else}
					<table class="w-full text-sm">
						<thead class="bg-muted">
							<tr>
								<th
									class="sticky top-0 bg-muted px-3 py-2 text-left font-semibold whitespace-nowrap"
									>Clave</th
								>
								<th
									class="sticky top-0 bg-muted px-3 py-2 text-left font-semibold whitespace-nowrap"
									>Nombre</th
								>
								<th
									class="sticky top-0 bg-muted px-3 py-2 text-left font-semibold whitespace-nowrap"
									>Tipo</th
								>
								<th
									class="sticky top-0 bg-muted px-3 py-2 text-left font-semibold whitespace-nowrap"
									>RFC</th
								>
								<th
									class="sticky top-0 bg-muted px-3 py-2 text-left font-semibold whitespace-nowrap"
									>Calles</th
								>
								<th
									class="sticky top-0 bg-muted px-3 py-2 text-left font-semibold whitespace-nowrap"
									>Núm. Ext</th
								>
								<th
									class="sticky top-0 bg-muted px-3 py-2 text-left font-semibold whitespace-nowrap"
									>CP</th
								>
								<th
									class="sticky top-0 bg-muted px-3 py-2 text-left font-semibold whitespace-nowrap"
									>Colonia</th
								>
								<th
									class="sticky top-0 bg-muted px-3 py-2 text-left font-semibold whitespace-nowrap"
									>Ciudad</th
								>
								<th
									class="sticky top-0 bg-muted px-3 py-2 text-center font-semibold whitespace-nowrap"
									>Acción</th
								>
							</tr>
						</thead>
						<tbody>
							{#if filteredItems.length === 0}
								<tr>
									<td colspan="10" class="px-4 py-8 text-center text-muted-foreground">
										No se encontraron resultados
									</td>
								</tr>
							{:else}
								{#each filteredItems as item}
									<tr
										class="cursor-pointer border-b transition-colors hover:bg-muted/50"
										onclick={() => selectItem(item)}
									>
										<td class="px-3 py-2.5 text-muted-foreground">{item.id || '-'}</td>
										<td class="px-3 py-2.5 font-medium whitespace-nowrap">{item.name || '-'}</td>
										<td class="px-3 py-2.5 text-center">
											<span
												class="inline-flex h-7 w-7 items-center justify-center rounded-full text-xs font-semibold {item.client_or_provider ===
												'provider'
													? 'bg-purple-100 text-purple-700'
													: item.client_or_provider === 'client'
														? 'bg-blue-100 text-blue-700'
														: 'bg-green-100 text-green-700'}"
											>
												{item.client_or_provider === 'provider'
													? 'P'
													: item.client_or_provider === 'client'
														? 'C'
														: 'A'}
											</span>
										</td>
										<td class="px-3 py-2.5 whitespace-nowrap">{item.rfc || '-'}</td>
										<td class="px-3 py-2.5 whitespace-nowrap">{item.address?.streets || '-'}</td>
										<td class="px-3 py-2.5 text-center whitespace-nowrap"
											>{item.address?.exterior_number || '-'}</td
										>
										<td class="px-3 py-2.5 text-center whitespace-nowrap"
											>{item.address?.postal_code || '-'}</td
										>
										<td class="px-3 py-2.5 whitespace-nowrap"
											>{item.address?.neighborhood || '-'}</td
										>
										<td class="px-3 py-2.5 whitespace-nowrap">{item.address?.city || '-'}</td>
										<td class="px-3 py-2.5 text-center whitespace-nowrap">
											<Button size="sm" variant="ghost" class="h-8">Seleccionar</Button>
										</td>
									</tr>
								{/each}
							{/if}
						</tbody>
					</table>
				{/if}
			</div>
		</div>

		<Dialog.Footer class="mt-4">
			<Button variant="outline" onclick={() => (dialogOpen = false)}>Cancelar</Button>
		</Dialog.Footer>
	</Dialog.Content>
</Dialog.Root>

<svelte:window onclick={closeContextMenu} />

<!-- Manual Context Menu -->
{#if contextMenu.open}
	<div
		class="animate-in fade-in-80 fixed z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md"
		style="top: {contextMenu.y}px; left: {contextMenu.x}px;"
	>
		<button
			class="relative flex w-full cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-none select-none hover:bg-accent hover:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50"
			onclick={(e) => {
				e.preventDefault();
				e.stopPropagation();
				previewReport();
			}}
		>
			<Eye class="mr-2 h-4 w-4" />
			Ver vista previa
		</button>
	</div>
{/if}
