<script lang="ts">
	import { onMount } from 'svelte';
	import { Button } from '$lib/components/ui/button';
	import * as Card from '$lib/components/ui/card';
	import { Input } from '$lib/components/ui/input';
	import { Label } from '$lib/components/ui/label';
	import { Separator } from '$lib/components/ui/separator';
	import { Textarea } from '$lib/components/ui/textarea';
	import * as Tabs from '$lib/components/ui/tabs';
	import * as Select from '$lib/components/ui/select';
	import { Switch } from '$lib/components/ui/switch';
	import { Checkbox } from '$lib/components/ui/checkbox';
	import { Badge } from '$lib/components/ui/badge';
	import {
		Loader2,
		ArrowLeft,
		Save,
		Truck,
		User,
		Calendar,
		FolderSearch,
		Clock,
		Calculator,
		Package,
		Info,
		AlertTriangle,
		Anchor,
		FileText,
		LayoutGrid,
		DollarSign,
		FileSpreadsheet,
		Globe,
		Users,
		Circle
	} from 'lucide-svelte';
	import { manifestApi, type Manifest } from '$lib/api/dashboard/a76/manifests';
	import { toast } from 'svelte-sonner';
	import { companyStore } from '$lib/stores/company.svelte';
	import { goto } from '$app/navigation';
	import InvoiceSelectionTable from '$lib/components/dashboard/export/manifest/invoice-selection-table.svelte';
	import { invoicesApi, type Invoice } from '$lib/api/dashboard/a76/invoices';

	// APIs para catálogos
	import { clientsProvidersApi } from '$lib/api/dashboard/a76/clients-providers';
	import { transportersApi } from '$lib/api/dashboard/a76/transporters';
	import { trailersApi } from '$lib/api/dashboard/a76/trailers';
	import { vehiclesApi } from '$lib/api/dashboard/a76/vehicles';
	import { transportModesApi } from '$lib/api/dashboard/reference_data/transport_modes';
	import { portsApi } from '$lib/api/dashboard/a76/general_catalogs/ports';
	import { customsBrokersApi } from '$lib/api/dashboard/a76/customs-brokers';

	// Componentes de selección (Modales)
	import ClientSelectorDialog from '$lib/components/dashboard/goods/modales/client-selector-dialog.svelte';
	import TransporterSelectorDialog from './modals/transporter-selector-dialog.svelte';
	import TrailerSelectorDialog from './modals/trailer-selector-dialog.svelte';
	import TransportModeSelectorDialog from './modals/transport-mode-selector-dialog.svelte';
	import VehicleSelectorDialog from './modals/vehicle-selector-dialog.svelte';
	import PortSelectorDialog from './modals/port-selector-dialog.svelte';
	import BrokerSelectorDialog from './modals/broker-selector-dialog.svelte';
	import ManifestDriverSubForm from './manifest-driver-subform.svelte';

	let { id }: { id?: string | null } = $props();

	let loading = $state(true);
	let saving = $state(false);
	let manifest = $state<Manifest | null>(null);
	let activeTab = $state('generales');

	const isNew = $derived(!id);

	// Visibility states for modals
	let showTransporterModal = $state(false);
	let showTrailerModal = $state(false);
	let showVehicleModal = $state(false);
	let showTransportModeModal = $state(false);
	let showExitPortModal = $state(false);
	let showEntryPortModal = $state(false);
	let showDestPortModal = $state(false);
	let showBrokerModal = $state(false);
	let showSentByModal = $state(false);
	let showConsignedToModal = $state(false);

	// Visual descriptions for IDs/Codes
	let selectedTransporterName = $state('');
	let selectedTrailerPlate = $state('');
	let selectedVehicleName = $state('');
	let selectedTransportTypeName = $state('');
	let selectedExitPortName = $state('');
	let selectedEntryPortName = $state('');
	let selectedDestPortName = $state('');
	let selectedBrokerName = $state('');
	let selectedSentByName = $state('');
	let selectedConsignedToName = $state('');

	// Helper state for date picker (formatting YYYYMMDD to YYYY-MM-DD and viceversa)
	let entryDateStr = $state('');

	$effect(() => {
		if (formData.entry_date) {
			const s = formData.entry_date.toString();
			if (s.length === 8) {
				entryDateStr = `${s.substring(0, 4)}-${s.substring(4, 6)}-${s.substring(6, 8)}`;
			}
		}
	});

	$effect(() => {
		if (entryDateStr) {
			formData.entry_date = parseInt(entryDateStr.replaceAll('-', ''));
		} else {
			formData.entry_date = undefined;
		}
	});

	// Form data state
	let formData = $state({
		manifest_number: '',
		carrier_code: '',
		entry_date: undefined as number | undefined,
		status: 'PENDIENTE',
		description: '',
		broker_code: '',
		person_in_charge: '',
		consigned_to: '',
		sent_by: '',
		foreign_exit_port: '',
		destination_port: '',
		entry_port: '',
		net_weight: 0,
		gross_weight: 0,
		total_value: 0,
		american_key: '',
		invoice_items_description: '',
		invoice_page_count: 0,
		precinct_number: '',
		arrival_time: '',
		is_draft: false,
		entry_type: '',
		is_hazardous: false,
		transport_key: '',
		transport_mode: '',
		trailer_number: '',
		status_description: '',
		vehicle_status: 'NUEVO'
	});

	// Consolidated Categorized Lists (Merges Available + Selected)
	let scaiiExpInvoices = $state<Invoice[]>([]);
	let scaiiReparInvoices = $state<Invoice[]>([]);
	let scafExpInvoices = $state<Invoice[]>([]);
	let scafReparInvoices = $state<Invoice[]>([]);

	let allDebugInvoicesCount = $state<number | null>(null);
	let lastFetchAttempt = $state<string>('Nunca');

	let invoicesLoading = $state(false);

	// Summary Calculations based on is_selected status
	const scaiiExpTotals = $derived({
		value: scaiiExpInvoices
			.filter((i) => i.is_selected)
			.reduce((sum, inv) => sum + Number(inv.financials?.value_me ?? 0), 0),
		weight: scaiiExpInvoices
			.filter((i) => i.is_selected)
			.reduce((sum, inv) => sum + Number(inv.financials?.gross_weight ?? 0), 0)
	});

	const scaiiReparTotals = $derived({
		value: scaiiReparInvoices
			.filter((i) => i.is_selected)
			.reduce((sum, inv) => sum + Number(inv.financials?.value_me ?? 0), 0),
		weight: scaiiReparInvoices
			.filter((i) => i.is_selected)
			.reduce((sum, inv) => sum + Number(inv.financials?.gross_weight ?? 0), 0)
	});

	const scafExpTotals = $derived({
		value: scafExpInvoices
			.filter((i) => i.is_selected)
			.reduce((sum, inv) => sum + Number(inv.financials?.value_me ?? 0), 0),
		weight: scafExpInvoices
			.filter((i) => i.is_selected)
			.reduce((sum, inv) => sum + Number(inv.financials?.gross_weight ?? 0), 0)
	});

	const scafReparTotals = $derived({
		value: scafReparInvoices
			.filter((i) => i.is_selected)
			.reduce((sum, inv) => sum + Number(inv.financials?.value_me ?? 0), 0),
		weight: scafReparInvoices
			.filter((i) => i.is_selected)
			.reduce((sum, inv) => sum + Number(inv.financials?.gross_weight ?? 0), 0)
	});

	// Load manifest data reactively
	$effect(() => {
		if (companyStore.activeCompany && !isNew && id) {
			// Only fetch if we haven't fetched yet or if ID changes (though ID is usually stable per page)
			// effectively, if we are loading and we have everything we need, Go.
			// Ideally we want to prevent double fetching, but fetchManifestData handles state.
			// Let's call it and ensure inside it handles the loading flag correctly.
			// We can check if we already have data for this ID to avoid spamming if multiple effects trigger,
			// but simplest is just call it.
			if (!manifest || manifest.id !== parseInt(id)) {
				fetchManifestData();
			}
		} else if (isNew) {
			// If new, stop loading immediately
			loading = false;
		} else if (!companyStore.activeCompany) {
			// Waiting for company... keep loading true
			loading = true;
		}
	});

	// Trigger invoice fetch when entering the tab or when manifest number changes
	$effect(() => {
		// Log for debugging
		if (activeTab === 'facturas_expo') {
			fetchInvoiceLists();
		}
	});

	// Fetch invoices for the selection tab - STRICT LINKING ONLY
	async function fetchInvoiceLists() {
		if (!companyStore.activeCompany) return;

		// If no manifest number, we cannot show linked invoices yet
		if (!formData.manifest_number) {
			scaiiExpInvoices = [];
			scaiiReparInvoices = [];
			scafExpInvoices = [];
			scafReparInvoices = [];
			return;
		}
		
		lastFetchAttempt = new Date().toLocaleTimeString();
		invoicesLoading = true;
		const companyId = companyStore.activeCompany.id;

		try {
			// Fetch ONLY invoices assigned to this manifest
			const res = await invoicesApi.list(companyId, 1, 100, {
				manifest_number: formData.manifest_number.trim()
			});

			// Filter for exports only in frontend to be safe
			const allInvoices = (res.data?.items || []).filter((inv) => inv.operation_type === 'exp');

			allDebugInvoicesCount = allInvoices.length;

			// Mark all as selected for visual consistency (since they ARE linked)
			allInvoices.forEach((inv) => (inv.is_selected = true));			

			// Helper to normalize system
			const getSystem = (s: string | undefined) => {
				if (!s) return '';
				const lower = s.toLowerCase();
				// Map legacy/alt names to canonical 'inventory' and 'fixed_asset'
				if (lower.includes('scaii') || lower.includes('inventory')) return 'inventory';
				if (lower.includes('scaf') || lower.includes('fixed_asset')) return 'fixed_asset';
				return lower;
			};

			// Helper to check if Repar request
			const isRepar = (t: string | undefined) => {
				return t === 'REPAR';
			};

			// Categorize
			// SCAII -> 'inventory'
			scaiiExpInvoices = allInvoices.filter(
				(inv) =>
					getSystem(inv.system ?? undefined) === 'inventory' &&
					!isRepar(inv.invoice_type ?? undefined)
			);
			scaiiReparInvoices = allInvoices.filter(
				(inv) =>
					getSystem(inv.system ?? undefined) === 'inventory' &&
					isRepar(inv.invoice_type ?? undefined)
			);

			// SCAF -> 'fixed_asset'
			scafExpInvoices = allInvoices.filter(
				(inv) =>
					getSystem(inv.system ?? undefined) === 'fixed_asset' &&
					!isRepar(inv.invoice_type ?? undefined)
			);
			scafReparInvoices = allInvoices.filter(
				(inv) =>
					getSystem(inv.system ?? undefined) === 'fixed_asset' &&
					isRepar(inv.invoice_type ?? undefined)
			);

		} catch (e) {
			console.error('Error fetching invoices:', e);
			toast.error('Error al cargar facturas');
		} finally {
			invoicesLoading = false;
		}
	}

	$effect(() => {
		if (activeTab === 'facturas_expo') {
			fetchInvoiceLists();
		}
	});

	function handleAssignToggle(invoice: Invoice) {
		// Read-only view as per request
		// toast.info("Edición de relación deshabilitada en esta vista");
	}

	async function fetchManifestData() {
		if (!id || !companyStore.activeCompany) return;

		loading = true;
		try {
			const response = await manifestApi.get(companyStore.activeCompany.id, parseInt(id));
			if (response.error) {
				toast.error(response.error);
				goto('/dashboard/export/manifest');
				return;
			}
			if (response.data) {
				manifest = response.data;
				Object.keys(formData).forEach((key) => {
					if (manifest && (manifest as any)[key] !== undefined) {
						(formData as any)[key] = (manifest as any)[key];
					}
				});

				// Manual mapping for UI specific fields
				if (manifest) {
					formData.precinct_number = manifest.seal_number || '';
					formData.entry_type = manifest.manifest_type || '';
					formData.transport_key = manifest.transport_code || '';
					formData.transport_mode = manifest.transport_mode || '';
					formData.is_hazardous =
						manifest.hazardous_material === 'S' || manifest.hazardous_material === 'Y';
					formData.american_key = manifest.broker_code || '';

					// Format time
					if (manifest.entry_hour) {
						// Assuming HHMM format integer from backend check or HH
						const timeStr = manifest.entry_hour.toString().padStart(4, '0');
						if (timeStr.length === 4) {
							formData.arrival_time = `${timeStr.substring(0, 2)}:${timeStr.substring(2, 4)}`;
						} else {
							formData.arrival_time = manifest.entry_hour.toString();
						}
					}

					formData.invoice_items_description = manifest.description || '';
				}
			}
		} catch (e) {
			console.error('Error fetching manifest:', e);
			toast.error('Error al cargar el manifiesto');
		} finally {
			loading = false;
			resolveDescriptions(); // Resolver nombres de catálogos
		}
	}

	// --- RESOLUCIÓN DE NOMBRES ---
	async function resolveDescriptions() {
		if (!companyStore.activeCompany) return;
		const companyId = companyStore.activeCompany.id;

		// Resolve Port names
		if (formData.foreign_exit_port && companyId) {
			portsApi
				.list(companyId, { port_code: formData.foreign_exit_port, page_size: 1 })
				.then((res) => {
					if (res.data && res.data.items?.[0]) {
						selectedExitPortName = res.data.items[0].description || res.data.items[0].port_code;
					}
				});
		}
		if (formData.entry_port && companyId) {
			portsApi.list(companyId, { port_code: formData.entry_port, page_size: 1 }).then((res) => {
				if (res.data && res.data.items?.[0]) {
					selectedEntryPortName = res.data.items[0].description || res.data.items[0].port_code;
				}
			});
		}
		if (formData.destination_port && companyId) {
			portsApi
				.list(companyId, { port_code: formData.destination_port, page_size: 1 })
				.then((res) => {
					if (res.data && res.data.items?.[0]) {
						selectedDestPortName = res.data.items[0].description || res.data.items[0].port_code;
					}
				});
		}

		// Resolve Transporter
		if (formData.carrier_code) {
			transportersApi
				.get(formData.carrier_code, companyId)
				.then((res) => {
					const data = (res as any).data || res;
					if (data) selectedTransporterName = data.name || '';
				})
				.catch(() => {});
		}

		// Resolve Trailer
		if (formData.trailer_number) {
			trailersApi
				.get(formData.trailer_number, companyId)
				.then((res) => {
					const data = (res as any).data || res;
					if (data) selectedTrailerPlate = data.plate_number || '';
				})
				.catch(() => {});
		}

		// Resolve Broker
		if (formData.american_key) {
			customsBrokersApi
				.get(formData.american_key, companyId.toString())
				.then((res) => {
					const data = (res as any).data || res;
					if (data) selectedBrokerName = data.name || data.broker_key || '';
				})
				.catch(() => {});
		}

		// Resolve Clients
		if (formData.sent_by) {
			const id = parseInt(formData.sent_by);
			if (!isNaN(id)) {
				clientsProvidersApi
					.get(id, companyId)
					.then((res) => {
						const data = (res as any).data || res;
						if (data) selectedSentByName = data.name || '';
					})
					.catch(() => {});
			}
		}
		if (formData.consigned_to) {
			const id = parseInt(formData.consigned_to);
			if (!isNaN(id)) {
				clientsProvidersApi
					.get(id, companyId)
					.then((res) => {
						const data = (res as any).data || res;
						if (data) selectedConsignedToName = data.name || '';
					})
					.catch(() => {});
			}
		}

		// Resolve Vehicle
		if (formData.transport_key) {
			vehiclesApi
				.get(formData.transport_key, companyId.toString())
				.then((res: any) => {
					if (res.data)
						selectedVehicleName = `${res.data.brand || ''} ${res.data.description || ''}`.trim();
				})
				.catch(() => {});
		}

		// Resolve Transport Mode
		if (formData.transport_mode) {
			transportModesApi
				.get(formData.transport_mode)
				.then((res: any) => {
					if (res.data) selectedTransportTypeName = res.data.name || '';
				})
				.catch(() => {});
		}
	}

	// --- MANEJADORES DE SELECCIÓN ---
	function handleTransporterSelect(item: any) {
		formData.carrier_code = item.transporter_key;
		selectedTransporterName = item.name;
	}

	function handleTrailerSelect(item: any) {
		formData.trailer_number = item.trailer_number;
		selectedTrailerPlate = item.plate_number || '';
	}

	function handleVehicleSelect(item: any) {
		formData.transport_key = item.vehicle_key;
		selectedVehicleName = `${item.brand || ''} ${item.description || ''}`.trim();
	}

	function handleTransportModeSelect(item: any) {
		formData.transport_mode = item.key;
		selectedTransportTypeName = item.name;
	}

	function handleExitPortSelect(item: any) {
		formData.foreign_exit_port = item.port_code;
		selectedExitPortName = item.description || '';
	}

	function handleEntryPortSelect(item: any) {
		formData.entry_port = item.port_code;
		selectedEntryPortName = item.description || '';
	}

	function handleDestPortSelect(item: any) {
		formData.destination_port = item.port_code;
		selectedDestPortName = item.description || '';
	}

	function handleBrokerSelect(item: any) {
		formData.american_key = item.broker_key;
		selectedBrokerName = item.name || item.broker_key;
	}

	function handleSentBySelect(client: any) {
		formData.sent_by = client.id.toString();
		selectedSentByName = client.name;
	}

	function handleConsignedToSelect(client: any) {
		formData.consigned_to = client.id.toString();
		selectedConsignedToName = client.name;
	}

	function handleTransporterClear() {
		formData.carrier_code = '';
		selectedTransporterName = '';
	}
	function handleTrailerClear() {
		formData.trailer_number = '';
		selectedTrailerPlate = '';
	}
	function handleVehicleClear() {
		formData.transport_key = '';
		selectedVehicleName = '';
	}
	function handleTransportModeClear() {
		formData.transport_mode = '';
		selectedTransportTypeName = '';
	}
	function handleExitPortClear() {
		formData.foreign_exit_port = '';
		selectedExitPortName = '';
	}
	function handleEntryPortClear() {
		formData.entry_port = '';
		selectedEntryPortName = '';
	}
	function handleDestPortClear() {
		formData.destination_port = '';
		selectedDestPortName = '';
	}
	function handleBrokerClear() {
		formData.american_key = '';
		selectedBrokerName = '';
	}
	function handleSentByClear() {
		formData.sent_by = '';
		selectedSentByName = '';
	}
	function handleConsignedToClear() {
		formData.consigned_to = '';
		selectedConsignedToName = '';
	}

	async function handleSubmit() {
		if (!companyStore.activeCompany) return;

		try {
			saving = true;
			if (!formData.manifest_number) {
				toast.error('El número de manifiesto es obligatorio');
				return;
			}

			const companyId = companyStore.activeCompany.id.toString();

			// Map form data to DTO
			const payload: any = {
				...formData,
				// Map specific fields and truncate to satisfy backend limits
				seal_number: formData.precinct_number?.substring(0, 30),
				manifest_type: formData.entry_type?.substring(0, 3),
				transport_code: formData.transport_key?.substring(0, 14),
				transport_mode: formData.transport_mode?.substring(0, 2),
				hazardous_material: formData.is_hazardous ? 'S' : 'N',
				broker_code: (formData.american_key || formData.broker_code)?.substring(0, 5),

				// Ensure correct types
				entry_hour: formData.arrival_time
					? parseInt(formData.arrival_time.replace(':', '').substring(0, 4))
					: undefined,

				// Map other fields that differ
				importer_details: '',
				description: formData.invoice_items_description || formData.description,

				// Port Codes Truncation
				foreign_exit_port: formData.foreign_exit_port?.substring(0, 6),
				destination_port: formData.destination_port?.substring(0, 6),
				entry_port: formData.entry_port?.substring(0, 6),
				carrier_code: formData.carrier_code?.substring(0, 5)
			};

			let savedManifestId: number | undefined;

			if (isNew) {
				const response = await manifestApi.create(companyId, payload);
				if (response.error) {
					toast.error(response.error);
					saving = false;
					return;
				}
				toast.success('Manifiesto creado correctamente');
				savedManifestId = response.data?.id;
			} else if (id) {
				const response = await manifestApi.update(companyId, parseInt(id), payload);
				if (response.error) {
					toast.error(response.error);
					saving = false;
					return;
				}
				toast.success('Manifiesto actualizado correctamente');
				savedManifestId = parseInt(id);
			}

			// BATCH SAVE INVOICES
			// Now that manifest is saved/updated, update the properly linked invoices.
			if (formData.manifest_number) {
				const allTrackedInvoices = [
					...scaiiExpInvoices,
					...scaiiReparInvoices,
					...scafExpInvoices,
					...scafReparInvoices
				];

				const updatePromises = [];				

				for (const inv of allTrackedInvoices) {
					const currentLink = inv.compliance_mx?.manifest_number;
					const shouldLink = inv.is_selected;

					// Case 1: Needs Linking (Selected but not currently linked to this manifest)
					if (shouldLink && currentLink !== formData.manifest_number) {					
						updatePromises.push(
							manifestApi.updateInvoiceCompliance(inv.id, companyId, formData.manifest_number)
						);
					}
					// Case 2: Needs Unlinking (Not Selected but currently linked to this manifest)
					else if (!shouldLink && currentLink === formData.manifest_number) {						
						updatePromises.push(manifestApi.updateInvoiceCompliance(inv.id, companyId, null));
					}
				}

				if (updatePromises.length > 0) {					
					await Promise.all(updatePromises);
					toast.success(`${updatePromises.length} facturas actualizadas`);									
				}
			}

			goto('/dashboard/export/manifest');
		} catch (error) {
			console.error(error);
			toast.error('Error al guardar el manifiesto');
		} finally {
			saving = false;
		}
	}

	function handleBack() {
		goto('/dashboard/export/manifest');
	}
</script>

<div class="space-y-3">
	{#if loading && !isNew}
		<div class="flex min-h-[400px] flex-col items-center justify-center space-y-4">
			<Loader2 class="h-8 w-8 animate-spin text-primary" />
			<p class="animate-pulse text-muted-foreground">Cargando datos del manifiesto...</p>
		</div>
	{:else}
		<div class="flex items-center gap-4">
			<Button variant="ghost" size="icon" onclick={handleBack} class="shrink-0">
				<ArrowLeft size={20} />
			</Button>
			<div class="space-y-0.5">
				<div class="flex items-center gap-3">
					<h1 class="text-3xl font-bold tracking-tight">
						{isNew ? 'Nuevo Manifiesto' : `Manifiesto #${id}`}
					</h1>
					<Badge variant={isNew ? 'default' : 'secondary'}>
						{isNew ? 'Nuevo' : 'Edición'}
					</Badge>
				</div>
				<p class="text-sm text-muted-foreground">
					{isNew ? 'Crea un nuevo registro de entrada' : `Manifest: ${formData.manifest_number}`}
				</p>
			</div>
		</div>

		<Separator />

		<!-- Main Content Area with padding for sticky footer -->
		<div class="mx-auto max-w-[1400px] pb-48">
			<Tabs.Root bind:value={activeTab}>
				<!-- Top Fields (Global across tabs) -->
				<!-- Top Fields (Global across tabs) - Compact & Clean (Like Invoice Form) -->
				<div class="mb-4 grid grid-cols-1 gap-3 border-b pb-4 md:grid-cols-4">
					<div class="space-y-0.5">
						<Label class="text-[9px] font-bold text-muted-foreground uppercase"
							>Número de Manifiesto</Label
						>
						<div class="relative">
							<Package class="absolute top-1.5 left-2 h-3 w-3 text-muted-foreground" />
							<Input
								bind:value={formData.manifest_number}
								class="h-7 pl-7 font-mono text-[10px]"
								placeholder="MAN-000"
							/>
						</div>
					</div>
					<div class="space-y-0.5">
						<Label class="text-[9px] font-bold text-muted-foreground uppercase"
							>Fecha Entrada/Arribo</Label
						>
						<div class="relative">
							<Calendar
								class="pointer-events-none absolute top-1.5 left-2 h-3 w-3 text-muted-foreground"
							/>
							<Input type="date" bind:value={entryDateStr} class="h-7 pl-7 text-[10px]" />
						</div>
					</div>
					<div class="space-y-0.5">
						<Label class="text-[9px] font-bold text-muted-foreground uppercase">Transportista</Label
						>
						<div class="flex gap-1">
							<div class="relative w-full">
								<Truck class="absolute top-1.5 left-2 h-3 w-3 text-muted-foreground" />
								<Input
									value={selectedTransporterName || formData.carrier_code}
									class="h-7 pl-7 font-mono text-[10px]"
									placeholder="Catálogo..."
									readonly
									onclick={() => (showTransporterModal = true)}
								/>
							</div>
							<Button
								variant="outline"
								size="icon"
								class="h-7 w-7 shrink-0"
								onclick={() => (showTransporterModal = true)}
							>
								<FolderSearch class="h-3 w-3" />
							</Button>
						</div>
					</div>
					<div class="space-y-0.5">
						<Label class="text-[9px] font-bold text-muted-foreground uppercase"
							>Persona a Cargo</Label
						>
						<div class="relative">
							<User class="absolute top-1.5 left-2 h-3 w-3 text-muted-foreground" />
							<Input
								bind:value={formData.person_in_charge}
								class="h-7 pl-7 text-[10px]"
								placeholder="Nombre completo"
							/>
						</div>
					</div>
				</div>

				<Tabs.Content value="generales" class="animate-in fade-in space-y-6 duration-300">
					<div class="grid grid-cols-1 gap-6 md:grid-cols-12">
						<div class="space-y-6 md:col-span-8">
							<!-- Puertos -->
							<Card.Root class="shadow-sm">
								<Card.Header class="bg-muted/30 pb-3">
									<Card.Title class="flex items-center gap-2 text-base">
										<Anchor class="h-4 w-4 text-primary" />
										Ruta y Puertos
									</Card.Title>
								</Card.Header>
								<Card.Content class="grid grid-cols-1 gap-6 pt-4 md:grid-cols-2">
									<div class="space-y-4">
										<div class="space-y-2">
											<Label class="text-sm">Salida de México</Label>
											<div class="flex gap-2">
												<Input
													bind:value={formData.foreign_exit_port}
													placeholder="Catálogo..."
													class="bg-muted/10 font-mono"
													readonly
													onclick={() => (showExitPortModal = true)}
												/>
												<Button
													variant="outline"
													size="icon"
													class="shrink-0"
													onclick={() => (showExitPortModal = true)}
													><FolderSearch class="h-4 w-4" /></Button
												>
											</div>
											{#if selectedExitPortName}
												<p class="truncate px-1 text-[10px] text-muted-foreground">
													{selectedExitPortName}
												</p>
											{/if}
										</div>
										<div class="space-y-2">
											<Label class="text-sm">Puerto Entrada EU</Label>
											<div class="flex gap-2">
												<Input
													bind:value={formData.entry_port}
													placeholder="Catálogo..."
													class="bg-muted/10 font-mono"
													readonly
													onclick={() => (showEntryPortModal = true)}
												/>
												<Button
													variant="outline"
													size="icon"
													class="shrink-0"
													onclick={() => (showEntryPortModal = true)}
													><FolderSearch class="h-4 w-4" /></Button
												>
											</div>
											{#if selectedEntryPortName}
												<p class="truncate px-1 text-[10px] text-muted-foreground">
													{selectedEntryPortName}
												</p>
											{/if}
										</div>
									</div>
									<div class="space-y-4">
										<div class="space-y-2">
											<Label class="text-sm">Destino en EU</Label>
											<div class="flex gap-2">
												<Input
													bind:value={formData.destination_port}
													placeholder="Catálogo..."
													class="bg-muted/10 font-mono"
													readonly
													onclick={() => (showDestPortModal = true)}
												/>
												<Button
													variant="outline"
													size="icon"
													class="shrink-0"
													onclick={() => (showDestPortModal = true)}
													><FolderSearch class="h-4 w-4" /></Button
												>
											</div>
											{#if selectedDestPortName}
												<p class="truncate px-1 text-[10px] text-muted-foreground">
													{selectedDestPortName}
												</p>
											{/if}
										</div>
										<div class="space-y-2">
											<Label class="text-sm">Estatus de Manifiesto</Label>
											<select
												bind:value={formData.status}
												class="flex h-10 w-full appearance-none rounded-md border border-input bg-background px-3 py-2 text-sm focus:ring-2 focus:ring-primary"
											>
												<option value="PENDIENTE">PENDIENTE</option>
												<option value="RECIBIDO">RECIBIDO</option>
												<option value="CANCELADO">CANCELADO</option>
											</select>
										</div>
									</div>
								</Card.Content>
							</Card.Root>

							<!-- Entidades -->
							<Card.Root class="shadow-sm">
								<Card.Header class="border-b pb-3">
									<Card.Title class="text-base">Entidades Comprometidas</Card.Title>
								</Card.Header>
								<Card.Content class="grid grid-cols-1 gap-x-8 gap-y-4 pt-4 md:grid-cols-2">
									<div class="space-y-2">
										<Label class="text-sm">Enviado por</Label>
										<div class="flex gap-2">
											<div class="relative w-full">
												<Input
													value={selectedSentByName || formData.sent_by}
													class="bg-muted/5 font-mono"
													placeholder="Catálogo..."
													readonly
													onclick={() => (showSentByModal = true)}
												/>
											</div>
											<Button
												variant="outline"
												size="icon"
												class="shrink-0"
												onclick={() => (showSentByModal = true)}
												><FolderSearch class="h-4 w-4" /></Button
											>
										</div>
										{#if selectedSentByName && selectedSentByName !== formData.sent_by}
											<!-- ID hidden as requested -->
										{/if}
									</div>
									<div class="space-y-2">
										<Label class="text-sm">Consignado a</Label>
										<div class="flex gap-2">
											<div class="relative w-full">
												<Input
													value={selectedConsignedToName || formData.consigned_to}
													class="bg-muted/5 font-mono"
													placeholder="Catálogo..."
													readonly
													onclick={() => (showConsignedToModal = true)}
												/>
											</div>
											<Button
												variant="outline"
												size="icon"
												class="shrink-0"
												onclick={() => (showConsignedToModal = true)}
												><FolderSearch class="h-4 w-4" /></Button
											>
										</div>
										{#if selectedConsignedToName && selectedConsignedToName !== formData.consigned_to}
											<!-- ID hidden as requested -->
										{/if}
									</div>
									<div class="space-y-2">
										<Label class="text-sm">Clave Americana</Label>
										<div class="flex gap-2">
											<div class="relative w-full">
												<Input
													value={selectedBrokerName || formData.american_key}
													class="bg-muted/5 font-mono"
													placeholder="Catálogo..."
													readonly
													onclick={() => (showBrokerModal = true)}
												/>
											</div>
											<Button
												variant="outline"
												size="icon"
												class="shrink-0"
												onclick={() => (showBrokerModal = true)}
												><FolderSearch class="h-4 w-4" /></Button
											>
										</div>
										{#if selectedBrokerName && selectedBrokerName !== formData.american_key}
											<!-- Name already shown in Input, no ID display needed -->
										{/if}
									</div>
								</Card.Content>
							</Card.Root>

							<!-- Partidas -->
							<Card.Root class="shadow-sm">
								<Card.Header>
									<Card.Title class="text-base">Descripción de Facturas Consolidadas</Card.Title>
								</Card.Header>
								<Card.Content>
									<Textarea
										bind:value={formData.invoice_items_description}
										placeholder="Descripción resumida por clase..."
										class="min-h-[120px] resize-none"
									/>
								</Card.Content>
							</Card.Root>
						</div>

						<div class="space-y-6 md:col-span-4">
							<!-- Pesos y Valores -->
							<Card.Root class="overflow-hidden shadow-sm">
								<div class="h-1 bg-green-600"></div>
								<Card.Header class="pb-2">
									<Card.Title
										class="flex items-center gap-2 text-sm font-bold text-muted-foreground uppercase"
									>
										<Globe class="h-4 w-4 text-green-600" />
										Valores Totales
									</Card.Title>
								</Card.Header>
								<Card.Content class="space-y-4">
									<div class="space-y-1">
										<Label class="text-xs">Peso Neto (KG)</Label>
										<Input type="number" step="0.01" bind:value={formData.net_weight} />
									</div>
									<div class="space-y-1">
										<Label class="text-xs">Peso Bruto (KG)</Label>
										<Input type="number" step="0.01" bind:value={formData.gross_weight} />
									</div>
									<div class="space-y-1">
										<Label class="text-xs">Valor Total (USD)</Label>
										<div class="relative">
											<DollarSign class="absolute top-2.5 left-3 h-4 w-4 text-muted-foreground" />
											<Input
												type="number"
												step="0.01"
												bind:value={formData.total_value}
												class="pl-9"
											/>
										</div>
									</div>
								</Card.Content>
							</Card.Root>

							<!-- Otros -->
							<Card.Root class="shadow-sm">
								<Card.Content class="space-y-4 p-6">
									<div class="space-y-2">
										<Label class="text-sm">Páginas/Facturas</Label>
										<Input type="number" bind:value={formData.invoice_page_count} />
									</div>
									<div class="space-y-2">
										<Label class="text-sm"># Precinto</Label>
										<Input bind:value={formData.precinct_number} />
									</div>
									<div class="space-y-2">
										<Label class="text-sm">Hora Entrada</Label>
										<div class="relative">
											<Clock class="absolute top-2.5 left-3 h-4 w-4 text-muted-foreground" />
											<Input bind:value={formData.arrival_time} class="pl-9" placeholder="12:00" />
										</div>
									</div>
								</Card.Content>
							</Card.Root>

							<!-- Calculadora Estetica -->
							<Card.Root class="border-dashed shadow-sm">
								<Card.Content class="space-y-3 p-4">
									<Button variant="outline" class="h-10 w-full gap-2">
										<Calculator class="h-4 w-4" />
										Calcular Totales
									</Button>
									<div class="flex items-center space-x-2 px-1">
										<Checkbox id="draft" bind:checked={formData.is_draft} />
										<Label for="draft" class="cursor-pointer text-sm">Borrador / Calcular</Label>
									</div>
								</Card.Content>
							</Card.Root>
						</div>
					</div>
				</Tabs.Content>

				<Tabs.Content value="cont" class="animate-in fade-in space-y-6 duration-300">
					<div class="grid grid-cols-1 gap-6 lg:grid-cols-12">
						<!-- Left Side: Attributes and Truck Info -->
						<div class="space-y-6 lg:col-span-5 xl:col-span-4">
							<!-- Attributes -->
							<Card.Root class="shadow-sm">
								<Card.Header class="pb-3">
									<Card.Title
										class="flex items-center gap-2 text-sm font-bold tracking-wider uppercase"
									>
										<Info class="h-4 w-4 text-primary" />
										Atributos
									</Card.Title>
								</Card.Header>
								<Card.Content class="space-y-4">
									<div class="space-y-2">
										<Label class="text-xs font-bold">Entry Type (Tipo Manifiesto)</Label>
										<Input bind:value={formData.entry_type} placeholder="Ej: General" class="h-9" />
									</div>
									<div
										class="flex items-center justify-between rounded-xl border border-orange-100 bg-orange-50/20 p-4"
									>
										<div class="flex gap-3">
											<AlertTriangle class="h-5 w-5 text-orange-600" />
											<div>
												<Label class="block text-sm font-bold">Material Peligroso</Label>
												<p class="text-xs text-muted-foreground italic">¿Riesgo?</p>
											</div>
										</div>
										<Switch bind:checked={formData.is_hazardous} />
									</div>
								</Card.Content>
							</Card.Root>

							<!-- Truck Details -->
							<Card.Root class="shadow-sm">
								<Card.Header class="pb-3">
									<Card.Title
										class="flex items-center gap-2 text-sm font-bold tracking-wider uppercase"
									>
										<Truck class="h-4 w-4 text-primary" />
										Vehículo
									</Card.Title>
								</Card.Header>
								<Card.Content class="space-y-4">
									<div class="grid grid-cols-2 gap-4">
										<div class="space-y-2">
											<Label class="text-xs font-bold uppercase">Clave Transporte</Label>
											<div class="flex gap-2">
												<Input
													bind:value={formData.transport_key}
													placeholder="..."
													readonly
													onclick={() => (showVehicleModal = true)}
													class="h-9 font-mono text-xs"
												/>
												<Button
													variant="outline"
													size="icon"
													class="h-9 w-9 shrink-0"
													onclick={() => (showVehicleModal = true)}
													><FolderSearch class="h-4 w-4" /></Button
												>
											</div>
										</div>
										<div class="space-y-2">
											<Label class="text-xs font-bold uppercase">Modo Transporte</Label>
											<div class="flex gap-2">
												<Input
													bind:value={formData.transport_mode}
													placeholder="..."
													readonly
													onclick={() => (showTransportModeModal = true)}
													class="h-9 font-mono text-xs"
												/>
												<Button
													variant="outline"
													size="icon"
													class="h-9 w-9 shrink-0"
													onclick={() => (showTransportModeModal = true)}
													><FolderSearch class="h-4 w-4" /></Button
												>
											</div>
										</div>
										<div class="space-y-2">
											<Label class="text-xs font-bold uppercase"># Trailer</Label>
											<div class="flex gap-2">
												<Input
													value={selectedTrailerPlate || formData.trailer_number}
													placeholder="..."
													readonly
													onclick={() => (showTrailerModal = true)}
													class="h-9 font-mono text-xs"
												/>
												<Button
													variant="outline"
													size="icon"
													class="h-9 w-9 shrink-0"
													onclick={() => (showTrailerModal = true)}
													><FolderSearch class="h-4 w-4" /></Button
												>
											</div>
										</div>
										<!-- Status Field (Vehicle specific, local state for now) -->
										<div class="space-y-2">
											<Label class="text-xs font-bold uppercase">Estatus Vehículo</Label>
											<Select.Root
												type="single"
												value={formData.vehicle_status}
												onValueChange={(v) => (formData.vehicle_status = v)}
											>
												<Select.Trigger class="h-9 px-3 text-xs">
													<div class="flex items-center gap-2">
														{#if formData.vehicle_status === 'NUEVO'}
															<Circle class="h-2 w-2 fill-green-500 text-green-500" />
														{:else if formData.vehicle_status === 'USADO'}
															<Circle class="h-2 w-2 fill-blue-500 text-blue-500" />
														{:else if formData.vehicle_status === 'CANCELADO'}
															<Circle class="h-2 w-2 fill-red-500 text-red-500" />
														{:else}
															<Circle class="h-2 w-2 fill-slate-300 text-slate-300" />
														{/if}
														<span class="truncate uppercase"
															>{formData.vehicle_status || 'Estado'}</span
														>
													</div>
												</Select.Trigger>
												<Select.Content>
													<Select.Item value="NUEVO" class="text-xs">
														<div class="flex items-center gap-2">
															<Circle class="h-2 w-2 fill-green-500 text-green-500" />
															NUEVO
														</div>
													</Select.Item>
													<Select.Item value="USADO" class="text-xs">
														<div class="flex items-center gap-2">
															<Circle class="h-2 w-2 fill-blue-500 text-blue-500" />
															USADO
														</div>
													</Select.Item>
													<Select.Item value="CANCELADO" class="text-xs">
														<div class="flex items-center gap-2">
															<Circle class="h-2 w-2 fill-red-500 text-red-500" />
															CANCELADO
														</div>
													</Select.Item>
												</Select.Content>
											</Select.Root>
										</div>
									</div>
									<Separator />
									<div class="space-y-2">
										<Label class="text-xs font-bold uppercase">Observaciones</Label>
										<Textarea
											bind:value={formData.status_description}
											placeholder="Notas sobre el estado..."
											class="min-h-[80px] text-xs"
										/>
									</div>
								</Card.Content>
							</Card.Root>
						</div>

						<!-- Right Side: Crew/Tripulación Table -->
						<div class="lg:col-span-7 xl:col-span-8">
							<ManifestDriverSubForm
								manifestNumber={formData.manifest_number}
								carrierName={selectedTransporterName || formData.carrier_code}
								isNewManifest={isNew}
							/>
						</div>
					</div>
				</Tabs.Content>
				<Tabs.Content value="facturas_expo" class="animate-in fade-in space-y-8 duration-300">
					<!-- Fila SCAII -->
					<div class="grid grid-cols-1 gap-6 lg:grid-cols-2">
						<!-- SCAII - EXP -->
						<div class="space-y-4">
							<div class="flex items-center justify-between">
								<div class="flex items-center gap-2">
									<div class="h-8 w-1 rounded-full bg-blue-600"></div>
									<h2 class="text-base font-bold">SCAII - EXPORTACIÓN (EXP)</h2>
								</div>
							</div>

							<InvoiceSelectionTable
								title="Facturas SCAII (EXP)"
								invoices={scaiiExpInvoices}
								loading={invoicesLoading}
								readOnly={true}
								onAction={handleAssignToggle}
							/>
						</div>

						<!-- SCAII - REPAR -->
						<div class="space-y-4">
							<div class="flex items-center justify-between">
								<div class="flex items-center gap-2">
									<div class="h-8 w-1 rounded-full bg-indigo-600"></div>
									<h2 class="text-base font-bold">SCAII - REPARACIÓN (REPAR)</h2>
								</div>
							</div>

							<InvoiceSelectionTable
								title="Facturas SCAII (REPAR)"
								invoices={scaiiReparInvoices}
								loading={invoicesLoading}
								readOnly={true}
								onAction={handleAssignToggle}
							/>
						</div>
					</div>

					<Separator />

					<!-- Fila SCAF -->
					<div class="grid grid-cols-1 gap-6 lg:grid-cols-2">
						<!-- SCAF - EXP -->
						<div class="space-y-4">
							<div class="flex items-center justify-between">
								<div class="flex items-center gap-2">
									<div class="h-8 w-1 rounded-full bg-green-600"></div>
									<h2 class="text-base font-bold">SCAF - EXPORTACIÓN (EXP)</h2>
								</div>
							</div>

							<InvoiceSelectionTable
								title="Facturas SCAF (EXP)"
								invoices={scafExpInvoices}
								loading={invoicesLoading}
								readOnly={true}
								onAction={handleAssignToggle}
							/>
						</div>

						<!-- SCAF - REPAR -->
						<div class="space-y-4">
							<div class="flex items-center justify-between">
								<div class="flex items-center gap-2">
									<div class="h-8 w-1 rounded-full bg-emerald-600"></div>
									<h2 class="text-base font-bold">SCAF - REPARACIÓN (REPAR)</h2>
								</div>
							</div>

							<InvoiceSelectionTable
								title="Facturas SCAF (REPAR)"
								invoices={scafReparInvoices}
								loading={invoicesLoading}
								readOnly={true}
								onAction={handleAssignToggle}
							/>
						</div>
					</div>
				</Tabs.Content>
			</Tabs.Root>
		</div>
	{/if}

	<!-- MODALES DE CATÁLOGO -->
	<TransporterSelectorDialog
		bind:open={showTransporterModal}
		onSelect={handleTransporterSelect}
		onClear={handleTransporterClear}
	/>
	<TrailerSelectorDialog bind:open={showTrailerModal} onSelect={handleTrailerSelect} onClear={handleTrailerClear} />
	<BrokerSelectorDialog bind:open={showBrokerModal} onSelect={handleBrokerSelect} onClear={handleBrokerClear} />
	<ClientSelectorDialog bind:open={showSentByModal} onSelect={handleSentBySelect} onClear={handleSentByClear} />
	<ClientSelectorDialog
		bind:open={showConsignedToModal}
		onSelect={handleConsignedToSelect}
		onClear={handleConsignedToClear}
	/>
	<VehicleSelectorDialog bind:open={showVehicleModal} onSelect={handleVehicleSelect} onClear={handleVehicleClear} />
	<TransportModeSelectorDialog
		bind:open={showTransportModeModal}
		onSelect={handleTransportModeSelect}
		onClear={handleTransportModeClear}
	/>

	<!-- Modales de Puertos -->
	<PortSelectorDialog bind:open={showExitPortModal} onSelect={handleExitPortSelect} onClear={handleExitPortClear} />
	<PortSelectorDialog bind:open={showEntryPortModal} onSelect={handleEntryPortSelect} onClear={handleEntryPortClear} />
	<PortSelectorDialog bind:open={showDestPortModal} onSelect={handleDestPortSelect} onClear={handleDestPortClear} />
</div>

<!-- Sticky Footer -->
<div
	class="fixed right-0 bottom-0 left-0 z-[50] 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] space-y-4 px-6 py-4">
		<!-- Tabs Navigation in Footer -->
		<Tabs.Root bind:value={activeTab}>
			<div class="w-full">
				<Tabs.List class="grid w-full grid-cols-3">
					<Tabs.Trigger
						value="generales"
						class="whitespace-nowrap data-[state=active]:bg-primary data-[state=active]:text-primary-foreground"
					>
						<FileText size={16} class="mr-2" />
						Generales
					</Tabs.Trigger>
					<Tabs.Trigger
						value="cont"
						class="whitespace-nowrap data-[state=active]:bg-primary data-[state=active]:text-primary-foreground"
					>
						<LayoutGrid size={16} class="mr-2" />
						Cont.
					</Tabs.Trigger>
					<Tabs.Trigger
						value="facturas_expo"
						class="whitespace-nowrap data-[state=active]:bg-primary data-[state=active]:text-primary-foreground"
					>
						<FileSpreadsheet size={16} class="mr-2" />
						Facturas de Expo
					</Tabs.Trigger>
				</Tabs.List>
			</div>
		</Tabs.Root>

		<!-- Bottom Action Buttons -->
		<div class="flex justify-end gap-3">
			<Button type="button" variant="outline" onclick={handleBack} disabled={saving}>
				Cancelar
			</Button>
			<Button onclick={handleSubmit} disabled={saving} class="min-w-[150px]">
				{#if saving}
					<Loader2 class="mr-2 h-4 w-4 animate-spin" />
					Guardando...
				{:else}
					<Save size={16} class="mr-2" />
					Guardar Cambios
				{/if}
			</Button>
		</div>
	</div>
</div>

<style>
	:global(body) {
		overflow-x: hidden;
	}

	select {
		background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M6 8l4 4 4-4'/%3e%3c/svg%3e");
		background-position: right 0.5rem center;
		background-repeat: no-repeat;
		background-size: 1.5em 1.5em;
		padding-right: 2.5rem;
	}
</style>
