<script lang="ts">
	import * as Dialog from '$lib/components/ui/dialog';
	import * as Select from '$lib/components/ui/select';
	import * as Tabs from '$lib/components/ui/tabs';
	import { Button } from '$lib/components/ui/button';
	import { Input } from '$lib/components/ui/input';
	import { Label } from '$lib/components/ui/label';
	import { Checkbox } from '$lib/components/ui/checkbox';
	import { toast } from 'svelte-sonner';
	import { Send, FileText, Settings, Database, Folder, X } from 'lucide-svelte';
	import ManifestSelectorModal from './edit/ManifestSelectorModal.svelte';
	import InvoiceSelectorModal from './edit/InvoiceSelectorModal.svelte';
	import PdfProgressDialog from '$lib/components/dashboard/invoices/pdf-progress-dialog.svelte';
	import PortSelectorDialog from '$lib/components/dashboard/export/manifest/modals/port-selector-dialog.svelte';
	import { reportsTransmissionApi } from '$lib/api/dashboard/a76/reports/reports-transmission';
	import {
		Table,
		TableBody,
		TableCell,
		TableHead,
		TableHeader,
		TableRow
	} from '$lib/components/ui/table';
	import { invoicesApi, type Invoice } from '$lib/api/dashboard/a76/invoices';
	import { companyStore } from '$lib/stores/company.svelte';
	import { manifestApi as manifestsApi } from '$lib/api/dashboard/a76/manifests';

	let { open = $bindable(false), invoice = null } = $props<{
		open: boolean;
		invoice?: any;
	}>();

	// --- STATE ---
	let interfaceType = $state('MAINX30');
	let movementType = $state('Exportacion');
	let regimen = $state('Temporal');
	let activeTab = $state('movimiento');

	let manifests = $state<string[]>([]);

	// Selector Modal State
	let isManifestSelectorOpen = $state(false);
	let currentManifestIndex = $state(0);

	// Invoice Manual State (12 slots)
	let manualInvoices = $state<string[]>([]);
	let isInvoiceSelectorOpen = $state(false);
	let currentInvoiceIndex = $state(0);

	// Progress Dialog State
	let isProgressOpen = $state(false);
	let taskId = $state<string | null>(null);
	let downloadUrl = $state<string | null>(null);
	let fileName = $state<string | null>(null);
	let progressTitle = $state('Generando Archivo de Transmisión');
	let isTemporalTask = $state(false);
	let isDefinitiveTask = $state(false);

	// Ports State
	let entryPort = $state('');
	let exitPort = $state('');
	let openEntryPortDialog = $state(false);
	let openExitPortDialog = $state(false);

	// Invoices State
	let invoices = $state<Invoice[]>([]);
	let loading = $state(false);
	let items = $state<any[]>([]); // manifest items
	let selectedItems = $state<Set<string>>(new Set());
	let selectedInvoices = $state<Set<number>>(new Set());
	// Assuming selectedItems and requestEmail are defined elsewhere or will be added
	// requestEmail removed as placeholder

	// Checkboxes State (matching backend schemas)
	let checks = $state({
		nomenclatura_factura: false,
		consolidar_rbs: false,
		emanifest_fast_blanco: false,
		no_enviar_emanifest: false,
		consolidar_partidas: false,
		main_x40_emanifest: false,
		main_x30_fedex: false,
		iv11: false,
		iv42: false
	});

	// --- OPTIONS ---
	const interfaceOptions = [
		{ value: 'MAINX30', label: 'MAINX30' },
		{ value: 'MAINX40', label: 'MAINX40' },
		{ value: 'EDI-EDA RB SYSTEMS', label: 'EDI-EDA RB SYSTEMS' },
		{ value: 'EDI-EDA EXPEDITORS', label: 'EDI-EDA EXPEDITORS' },
		{ value: 'EDI KNEXPRESS', label: 'EDI KNEXPRESS' },
		{ value: 'EDI-EDA V2', label: 'EDI-EDA V2' }
	];

	const movementOptions = [
		{ value: 'Exportacion', label: 'Exportación' },
		{ value: 'Importacion', label: 'Importación' }
	];

	// --- ACTIONS ---
	function handleClose() {
		open = false;
	}

	async function handleAction() {
		if (movementType === 'Importacion') {
			const validInvoices = manualInvoices.filter((i) => i && i.trim() !== '');
			if (validInvoices.length === 0) {
				toast.error('Debe seleccionar al menos una factura');
				return;
			}

			if (!entryPort || !exitPort) {
				toast.error('Debe seleccionar tanto el puerto de entrada como el de salida');
				return;
			}

			const payload: any = {
				regimen,
				facturas: validInvoices,
				entry_port: entryPort,
				exit_port: exitPort,
				...checks
			};

			try {
				let res;
				if (regimen === 'Definitiva' || regimen === 'DEFINITIVO SCAF') {
					res = await reportsTransmissionApi.triggerDefinitiveGeneration(payload);
					isDefinitiveTask = true;
					isTemporalTask = false;
				} else {
					res = await reportsTransmissionApi.triggerTemporalGeneration(payload);
					isTemporalTask = true;
					isDefinitiveTask = false;
				}

				if (res.task_id) {
					taskId = res.task_id;
					isProgressOpen = true;
					downloadUrl = null;
					fileName = null;
				}
			} catch (error) {
				console.error('Error triggering transmission file generation:', error);
				toast.error('Error al iniciar la generación del archivo');
			}
		} else {
			// Exportacion Logic (Manifests)
			const validManifests = manifests.filter((m) => m && m.trim() !== '');

			if (validManifests.length === 0) {
				toast.error('Debe seleccionar al menos un manifiesto');
				return;
			}

			const payload: any = {
				manifiestos: validManifests,
				...checks
			};

			try {
				const res = await reportsTransmissionApi.triggerGeneration(payload);
				isTemporalTask = false;

				if (res.task_id) {
					taskId = res.task_id;
					isProgressOpen = true;
					downloadUrl = null;
					fileName = null;
				}
			} catch (error) {
				console.error('Error triggering transmission file generation:', error);
				toast.error('Error al iniciar la generación del archivo');
			}
		}
	}

	async function loadManifests() {
		if (!companyStore.activeCompany?.id) return;
		loading = true;
		try {
			// If Importacion, load Invoices instead
			if (movementType === 'Importacion') {
				let filters: any = {
					operation_type: 'imp'
				};

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

				const res = await invoicesApi.list(companyStore.activeCompany.id, 1, 100, filters);
				invoices = res?.data?.items || [];
			} else {
				// Existing Manifest Logic
				const res = await manifestsApi.list(companyStore.activeCompany.id, {
					page: 1,
					page_size: 100,
					status: 'open'
				});
				items = res?.data?.items || [];
			}
		} catch (error) {
			console.error('Error loading data:', error);
			toast.error('Error al cargar datos');
		} finally {
			loading = false;
		}
	}

	$effect(() => {
		if (open && companyStore.activeCompany?.id) {
			loadManifests();
			// Pre-fill first slot if we have a specific invoice and it's empty
			if (invoice?.invoice_number && !manualInvoices.includes(invoice.invoice_number)) {
				manualInvoices.push(invoice.invoice_number);
			}
		}
	});

	// Re-load when movement type changes
	// Re-load when movement type or regimen changes
	$effect(() => {
		if (open && movementType) {
			// Trigger re-load when movementType or regimen changes
			// We access regimen here so it becomes a dependency
			const currentRegimen = regimen;
			loadManifests();
			// Clear selections
			selectedItems.clear();
			selectedInvoices.clear();
		}
	});

	function openManifestSelector(index: number) {
		currentManifestIndex = index;
		isManifestSelectorOpen = true;
	}

	function handleManifestSelect(manifest: any) {
		if (currentManifestIndex === -1) {
			manifests.push(manifest.manifest_number);
		} else {
			manifests[currentManifestIndex] = manifest.manifest_number;
		}
		isManifestSelectorOpen = false;
	}

	function openInvoiceSelector(index: number) {
		currentInvoiceIndex = index;
		isInvoiceSelectorOpen = true;
	}

	function handleInvoiceSelect(invoice: any) {
		if (currentInvoiceIndex === -1) {
			manualInvoices.push(invoice.invoice_number);
		} else {
			manualInvoices[currentInvoiceIndex] = invoice.invoice_number;
		}
		isInvoiceSelectorOpen = false;
	}

	// This function is expected by PdfProgressDialog to check status
	async function checkTaskStatus(id: string) {
		if (isDefinitiveTask) {
			return await reportsTransmissionApi.getDefinitiveTaskStatus(id);
		}
		if (isTemporalTask) {
			return await reportsTransmissionApi.getTemporalTaskStatus(id);
		}
		return await reportsTransmissionApi.getTaskStatus(id);
	}

	function handleDownloadComplete(result: any) {
		if (result && result.content && result.file_name) {
			try {
				// Convert base64 to blob
				const byteCharacters = atob(result.content);
				const byteNumbers = new Array(byteCharacters.length);
				for (let i = 0; i < byteCharacters.length; i++) {
					byteNumbers[i] = byteCharacters.charCodeAt(i);
				}
				const byteArray = new Uint8Array(byteNumbers);
				const blob = new Blob([byteArray], {
					type: result.media_type || 'application/octet-stream'
				});

				// Create link and download
				const url = window.URL.createObjectURL(blob);
				// @ts-ignore
				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('Archivo descargado correctamente');
			} catch (e) {
				console.error('Error downloading file', e);
				toast.error('Error al descargar el archivo');
			}
		}

		isProgressOpen = false;
		taskId = null;
	}
</script>

<Dialog.Root bind:open>
	<Dialog.Content class="sm:max-w-[1200px]">
		<Dialog.Header>
			<Dialog.Title>Interfase Broker Americano</Dialog.Title>
			<Dialog.Description>
				Configura la transferencia electrónica para la factura {invoice?.invoice_number || ''}
			</Dialog.Description>
		</Dialog.Header>

		<div class="space-y-4 py-2">
			<!-- TOP HEADER INPUTS -->
			<div class="grid grid-cols-1 gap-4 rounded-lg border p-3 md:grid-cols-2">
				<div class="grid gap-2">
					<Label>INTERFASE</Label>
					<Select.Root type="single" bind:value={interfaceType}>
						<Select.Trigger>{interfaceType}</Select.Trigger>
						<Select.Content>
							{#each interfaceOptions as opt}
								<Select.Item value={opt.value} label={opt.label} />
							{/each}
						</Select.Content>
					</Select.Root>
				</div>
				<div class="grid gap-2">
					<Label>Movimiento</Label>
					<Select.Root type="single" bind:value={movementType}>
						<Select.Trigger>{movementType}</Select.Trigger>
						<Select.Content>
							{#each movementOptions as opt}
								<Select.Item value={opt.value} label={opt.label} />
							{/each}
						</Select.Content>
					</Select.Root>
				</div>
				{#if movementType === 'Importacion'}
					<div class="grid gap-2">
						<Label>Regimen</Label>
						<Select.Root type="single" bind:value={regimen}>
							<Select.Trigger>{regimen}</Select.Trigger>
							<Select.Content>
								<Select.Item value="Temporal" label="Temporal" />
								<Select.Item value="Definitiva" label="Definitiva" />
								<Select.Item value="TEMPORAL SCAF" label="TEMPORAL SCAF" />
								<Select.Item value="DEFINITIVO SCAF" label="DEFINITIVO SCAF" />
							</Select.Content>
						</Select.Root>
					</div>
				{/if}
			</div>

			<!-- MAIN TABS -->
			<Tabs.Root bind:value={activeTab} class="w-full">
				<!-- TAB: MOVIMIENTO -->
				<Tabs.Content value="movimiento" class="space-y-4 pt-2">
					<div class="flex flex-col gap-4 md:flex-row">
						<!-- LEFT: Manifests Table -->
						<div class="flex-1 space-y-3">
							{#if movementType === 'Exportacion'}
								<div class="flex items-center justify-between py-1">
									<Label class="text-base font-medium">MANIFIESTOS (ENTRYS)</Label>
								</div>

								<div class="grid grid-cols-2 gap-3 md:grid-cols-3 lg:grid-cols-4">
									{#each manifests as m, i}
										<div
											class="group relative flex flex-col items-center justify-center rounded-lg border-2 border-solid border-blue-500 bg-blue-50/30 p-4 transition-all"
											role="button"
											tabindex="0"
											onclick={() => openManifestSelector(i)}
											onkeydown={(e) =>
												(e.key === 'Enter' || e.key === ' ') && openManifestSelector(i)}
										>
											<span class="absolute top-1 left-2 text-[10px] font-bold text-blue-400"
												>{i + 1}</span
											>
											<div
												class="w-full cursor-pointer truncate text-center text-sm font-semibold text-blue-700"
											>
												{m}
											</div>
											<button
												class="absolute -top-2 -right-2 z-20 rounded-full bg-destructive p-1 text-white shadow-md hover:scale-110 active:scale-95"
												onclick={(e) => {
													e.preventDefault();
													e.stopPropagation();
													manifests.splice(i, 1);
												}}
											>
												<X class="h-3 w-3" />
											</button>
										</div>
									{/each}

									<!-- Add Slot -->
									<div
										class="flex h-[72px] cursor-pointer flex-col items-center justify-center rounded-lg border-2 border-dashed border-muted p-4 transition-all hover:border-blue-400 hover:bg-blue-50/50"
										role="button"
										tabindex="0"
										onclick={() => openManifestSelector(-1)}
										onkeydown={(e) =>
											(e.key === 'Enter' || e.key === ' ') && openManifestSelector(-1)}
									>
										<Folder class="mb-1 h-4 w-4 text-muted-foreground" />
										<span class="text-xs font-medium text-muted-foreground">Agregar...</span>
									</div>
								</div>
							{/if}

							<div class="rounded-md border p-3">
								{#if movementType === 'Importacion'}
									<div class="mb-2 text-base font-medium">FACTURAS ({regimen?.toUpperCase()})</div>
									<div class="grid grid-cols-2 gap-3 md:grid-cols-3 lg:grid-cols-4">
										{#each manualInvoices as m, i}
											<div
												class="group relative flex flex-col items-center justify-center rounded-lg border-2 border-solid border-emerald-500 bg-emerald-50/30 p-4 transition-all"
												role="button"
												tabindex="0"
												onclick={() => openInvoiceSelector(i)}
												onkeydown={(e) =>
													(e.key === 'Enter' || e.key === ' ') && openInvoiceSelector(i)}
											>
												<span class="absolute top-1 left-2 text-[10px] font-bold text-emerald-400"
													>{i + 1}</span
												>
												<div
													class="w-full cursor-pointer truncate text-center text-sm font-semibold text-emerald-700"
												>
													{m}
												</div>
												<button
													class="absolute -top-2 -right-2 z-20 rounded-full bg-destructive p-1 text-white shadow-md hover:scale-110 active:scale-95"
													onclick={(e) => {
														e.preventDefault();
														e.stopPropagation();
														manualInvoices.splice(i, 1);
													}}
												>
													<X class="h-3 w-3" />
												</button>
											</div>
										{/each}

										<!-- Add Slot -->
										<div
											class="flex h-[72px] cursor-pointer flex-col items-center justify-center rounded-lg border-2 border-dashed border-muted p-4 transition-all hover:border-emerald-400 hover:bg-emerald-50/50"
											role="button"
											tabindex="0"
											onclick={() => openInvoiceSelector(-1)}
											onkeydown={(e) =>
												(e.key === 'Enter' || e.key === ' ') && openInvoiceSelector(-1)}
										>
											<Folder class="mb-1 h-4 w-4 text-muted-foreground" />
											<span class="text-xs font-medium text-muted-foreground">Agregar...</span>
										</div>
									</div>
								{/if}
							</div>

							<!-- Ports Selection (Only for Importacion) -->
							{#if movementType === 'Importacion'}
								<div class="mt-2 grid grid-cols-2 gap-4">
									<div class="space-y-2">
										<Label>Puerto Entrada</Label>
										<div class="relative">
											<Input bind:value={entryPort} placeholder="Seleccionar puerto..." readonly />
											<div class="absolute top-0 right-0 flex h-full">
												{#if entryPort}
													<Button
														variant="ghost"
														size="icon"
														onclick={() => (entryPort = '')}
														title="Limpiar"
													>
														<X class="h-4 w-4 text-muted-foreground hover:text-destructive" />
													</Button>
												{/if}
												<Button
													variant="ghost"
													size="icon"
													onclick={() => (openEntryPortDialog = true)}
													title="Seleccionar"
												>
													<Folder class="h-4 w-4" />
												</Button>
											</div>
										</div>
									</div>
									<div class="space-y-2">
										<Label>Puerto Salida</Label>
										<div class="relative">
											<Input bind:value={exitPort} placeholder="Seleccionar puerto..." readonly />
											<div class="absolute top-0 right-0 flex h-full">
												{#if exitPort}
													<Button
														variant="ghost"
														size="icon"
														onclick={() => (exitPort = '')}
														title="Limpiar"
													>
														<X class="h-4 w-4 text-muted-foreground hover:text-destructive" />
													</Button>
												{/if}
												<Button
													variant="ghost"
													size="icon"
													onclick={() => (openExitPortDialog = true)}
													title="Seleccionar"
												>
													<Folder class="h-4 w-4" />
												</Button>
											</div>
										</div>
									</div>
								</div>
							{/if}
						</div>
					</div>

					<!-- BOTTOM: Checklists -->
					<div class="border-t pt-2">
						<Label class="mb-2 block text-base font-medium">Opciones de Procesamiento</Label>
						<div class="grid grid-cols-1 gap-2 md:grid-cols-2 lg:grid-cols-4">
							<div class="flex items-start space-x-2">
								<Checkbox id="chk0" bind:checked={checks.nomenclatura_factura} />
								<Label for="chk0" class="cursor-pointer pt-0.5 text-sm leading-none font-normal">
									Consolidar por Factura (Nomenclatura)
								</Label>
							</div>

							<div class="flex items-start space-x-2">
								<Checkbox id="chk1" bind:checked={checks.consolidar_rbs} />
								<Label for="chk1" class="cursor-pointer pt-0.5 text-sm leading-none font-normal">
									Consolidar por fracción solamente Archivo EDI de RB System
								</Label>
							</div>

							<div class="flex items-start space-x-2">
								<Checkbox id="chk2" bind:checked={checks.emanifest_fast_blanco} />
								<Label for="chk2" class="cursor-pointer pt-0.5 text-sm leading-none font-normal">
									E-Manifest y Fast en Blanco
								</Label>
							</div>

							<div class="flex items-start space-x-2">
								<Checkbox id="chk3" bind:checked={checks.no_enviar_emanifest} />
								<Label for="chk3" class="cursor-pointer pt-0.5 text-sm leading-none font-normal">
									No enviar E-Manifest
								</Label>
							</div>

							<div class="flex items-start space-x-2">
								<Checkbox id="chk4" bind:checked={checks.consolidar_partidas} />
								<Label for="chk4" class="cursor-pointer pt-0.5 text-sm leading-none font-normal">
									Consolidar Partidas (XML OPTIMA Y RBS2)
								</Label>
							</div>

							<div class="flex items-start space-x-2">
								<Checkbox id="chk5" bind:checked={checks.main_x40_emanifest} />
								<Label for="chk5" class="cursor-pointer pt-0.5 text-sm leading-none font-normal">
									Main X40 E-Manifest
								</Label>
							</div>

							<div class="flex items-start space-x-2">
								<Checkbox id="chk6" bind:checked={checks.main_x30_fedex} />
								<Label for="chk6" class="cursor-pointer pt-0.5 text-sm leading-none font-normal">
									Main X30 (FEDEX)
								</Label>
							</div>

							<div class="flex items-start space-x-2">
								<Checkbox id="chk7" bind:checked={checks.iv11} />
								<Label for="chk7" class="cursor-pointer pt-0.5 text-sm leading-none font-normal">
									IV11
								</Label>
							</div>

							<div class="flex items-start space-x-2">
								<Checkbox id="chk8" bind:checked={checks.iv42} />
								<Label for="chk8" class="cursor-pointer pt-0.5 text-sm leading-none font-normal">
									IV42
								</Label>
							</div>
						</div>
					</div>
				</Tabs.Content>

				<!-- TAB: RESPALDOS -->
				<Tabs.Content
					value="respaldos"
					class="flex min-h-[200px] items-center justify-center rounded-md border bg-muted/10"
				>
					<div class="text-center text-muted-foreground">
						<Database class="mx-auto mb-2 h-8 w-8 opacity-50" />
						<p>Configuración de respaldos (Pendiente)</p>
					</div>
				</Tabs.Content>

				<!-- TAB: CONFIGURACION -->
				<Tabs.Content
					value="configuracion"
					class="flex min-h-[200px] items-center justify-center rounded-md border bg-muted/10"
				>
					<div class="text-center text-muted-foreground">
						<Settings class="mx-auto mb-2 h-8 w-8 opacity-50" />
						<p>Configuración general (Pendiente)</p>
					</div>
				</Tabs.Content>

				<!-- TABS LIST MOVED TO BOTTOM -->
				<Tabs.List class="mt-4 grid w-full grid-cols-3">
					<Tabs.Trigger value="movimiento">
						<FileText class="mr-2 h-4 w-4" /> Movimiento
					</Tabs.Trigger>
					<Tabs.Trigger value="respaldos">
						<Database class="mr-2 h-4 w-4" /> Respaldos
					</Tabs.Trigger>
					<Tabs.Trigger value="configuracion">
						<Settings class="mr-2 h-4 w-4" /> Configuración
					</Tabs.Trigger>
				</Tabs.List>
			</Tabs.Root>
		</div>

		<Dialog.Footer>
			<Button variant="outline" onclick={handleClose}>Cerrar</Button>
			<Button onclick={handleAction} class="bg-blue-600 text-white shadow hover:bg-blue-700">
				<Send class="mr-2 h-4 w-4" />
				Generar Archivo
			</Button>
		</Dialog.Footer>
	</Dialog.Content>

	<ManifestSelectorModal bind:open={isManifestSelectorOpen} onSelect={handleManifestSelect} />

	<InvoiceSelectorModal
		bind:open={isInvoiceSelectorOpen}
		{regimen}
		onSelect={handleInvoiceSelect}
	/>

	{#if taskId}
		<PdfProgressDialog
			bind:open={isProgressOpen}
			{taskId}
			title={progressTitle}
			getStatus={checkTaskStatus}
			onComplete={handleDownloadComplete}
			onClose={() => (isProgressOpen = false)}
		/>
	{/if}

	<PortSelectorDialog
		bind:open={openEntryPortDialog}
		onSelect={(item) => (entryPort = item.port_code)}
	/>

	<PortSelectorDialog
		bind:open={openExitPortDialog}
		onSelect={(item) => (exitPort = item.port_code)}
	/>
</Dialog.Root>
