<script lang="ts">
	import { page } from '$app/stores';
	import { goto } from '$app/navigation';
	import { companyStore } from '$lib/stores/company.svelte';
	import {
		customsBrokersApi,
		type CreateCustomsBrokerData
	} from '$lib/api/dashboard/a76/customs-brokers';

	// UI Components
	import CountryDialog from '$lib/components/dashboard/invoices/edit/items/fa/country-dialog.svelte';
	import StateDialog from '$lib/components/dashboard/invoices/edit/items/fa/state-dialog.svelte';
	import { Button } from '$lib/components/ui/button';
	import { Input } from '$lib/components/ui/input';
	import { Label } from '$lib/components/ui/label';
	import { Separator } from '$lib/components/ui/separator';
	import { Badge } from '$lib/components/ui/badge';
	import * as Tabs from '$lib/components/ui/tabs';
	import * as Card from '$lib/components/ui/card';
	import * as Select from '$lib/components/ui/select';
	import {
		ArrowLeft,
		Loader2,
		Save,
		User,
		Phone,
		MapPin,
		Settings,
		FileText,
		Hash,
		FileKey,
		Key,
		Globe,
		Folder,
		Mail,
		UserRound,
		Fingerprint,
		Lock,
		Signature,
		Archive,
		ShieldCheck
	} from 'lucide-svelte';
	import { toast } from 'svelte-sonner';
	import { useShortcuts } from '$lib/hooks/use-shortcuts';
	import { obtenerAtajosEdicionAgente } from '$lib/config/shortcuts/dashboard/customs_brokers/edit';

	// --- 1. LÓGICA DE IDENTIFICACIÓN ---
	let routeId = $derived($page.params.id);
	let isEdit = $derived(!!routeId && routeId !== 'new');
	let title = $derived(isEdit ? 'Editar Agente Aduanal' : 'Nuevo Agente Aduanal');

	// --- 2. ESTADO ---
	let loading = $state(false);
	let activeTab = $state('general');
	let error = $state<string | null>(null);
	let dataLoaded = $state(false);
	let showCountryDialog = $state(false);
	let showStateDialog = $state(false);

	let formData = $state<CreateCustomsBrokerData>({
		broker_key: '',
		license: '',
		name: '',
		tax_id: '',
		email: '',
		phone: '',
		fax: '',
		contact: '',
		address: '',
		postal_code: '',
		city: '',
		state: '',
		country: 'MEX',
		type: '',
		personal_id: '',
		position: '',
		company: '',
		company_id: ''
	});

	let vuData = $state({
		certificate_path: '',
		key_path: '',
		xml_files_path: '',
		fiel_access_key: '',
		doda_web_service_user: '',
		doda_web_service_access_key: '',
		doda_certificate_path: '',
		doda_key_path: '',
		doda_fiel_access_key: '',
		doda_xml_files_path: '',
		web_service_user: '',
		web_service_access_key: '',
		query_tax_id: '',
		vu_email: '',
		vu_figure_type: '',
		fiel_format: '',
		access_key: '',
		signature_read_path: '',
		archive_path: ''
	});

	let brokerKeyError = $state(false);
	let licenseError = $state(false);
	let brokerKeyTimeout: ReturnType<typeof setTimeout>;
	let licenseTimeout: ReturnType<typeof setTimeout>;

	// --- 3. CARGA DE DATOS REACTIVA ---
	$effect(() => {
		const company = companyStore.activeCompany;
		if (company && isEdit && routeId && !dataLoaded && !loading) {
			loadBrokerData(routeId, company.id.toString());
		} else if (company && !isEdit) {
			formData.company_id = company.id.toString();
		}
	});

	// --- 5. FUNCIONES ---
	function handleLocalFileSelect(event: Event, targetKey: keyof typeof vuData) {
		const input = event.target as HTMLInputElement;
		const file = input.files?.[0];
		if (file) {
			vuData[targetKey] = file.name;
			toast.success(`Archivo ${file.name} seleccionado`);
		}
	}

	async function loadBrokerData(key: string, cId: string) {
		if (!key || key === 'undefined') return;
		loading = true;
		try {
			const res = await customsBrokersApi.get(key, cId);
			const d = (res as any).data || res; // Handle wrapper or direct

			if (d && !d.error) {
				// Mapeo exhaustivo para asegurar reactividad
				formData = {
					broker_key: d.broker_key || '',
					license: d.license || '',
					name: d.name || '',
					tax_id: d.tax_id || '',
					email: d.email || '',
					phone: d.phone || '',
					fax: d.fax || '',
					contact: d.contact || '',
					address: d.address || '',
					postal_code: d.postal_code || '',
					city: d.city || '',
					state: d.state || '',
					country: d.country || 'MEX',
					type: d.type || '',
					personal_id: d.personal_id || '',
					position: d.position || '',
					company: d.company || '',
					company_id: cId
				};
				if (d.vu) {
					vuData = {
						certificate_path: d.vu.certificate_path || '',
						key_path: d.vu.key_path || '',
						xml_files_path: d.vu.xml_files_path || '',
						fiel_access_key: d.vu.fiel_access_key || '',
						doda_web_service_user: d.vu.doda_web_service_user || '',
						doda_web_service_access_key: d.vu.doda_web_service_access_key || '',
						doda_certificate_path: d.vu.doda_certificate_path || '',
						doda_key_path: d.vu.doda_key_path || '',
						doda_fiel_access_key: d.vu.doda_fiel_access_key || '',
						doda_xml_files_path: d.vu.doda_xml_files_path || '',
						web_service_user: d.vu.web_service_user || '',
						web_service_access_key: d.vu.web_service_access_key || '',
						query_tax_id: d.vu.query_tax_id || '',
						vu_email: d.vu.vu_email || '',
						vu_figure_type: d.vu.vu_figure_type || '',
						fiel_format: d.vu.fiel_format || '',
						access_key: d.vu.access_key || '',
						signature_read_path: d.vu.signature_read_path || '',
						archive_path: d.vu.archive_path || ''
					};
				}
				dataLoaded = true;
			} else if (d.error) {
				error = d.error as string;
				toast.error(error);
			}
		} catch (e: any) {
			error = 'Error al conectar con el servidor';
			toast.error(error);
		} finally {
			loading = false;
		}
	}

	function handleCountrySelect(country: any) {
		const nextCountry = country.m3_key || country.mex_key || country.ame_key;
		if (formData.country !== nextCountry) {
			formData.state = '';
		}
		formData.country = nextCountry;
	}

	function handleStateSelect(state: any) {
		formData.state = state.m3_key || state.mex_key || state.ame_key;
	}

	// --- 4. GUARDADO ---
	async function handleSave() {
		if (!companyStore.activeCompany) {
			toast.error('Selecciona una compañía');
			return;
		}
		if (!formData.broker_key?.trim() || !formData.license?.trim()) {
			error = 'Clave y Patente son obligatorios';
			toast.error(error);
			return;
		}

		if (formData.broker_key.length > 5) {
			error = 'La Clave del Agente no debe superar los 5 caracteres';
			toast.error(error);
			return;
		}

		if (formData.license && formData.license.length > 4) {
			error = 'La Patente no debe superar los 4 dígitos';
			toast.error(error);
			return;
		}

		loading = true;
		error = null;
		try {
			const cId = companyStore.activeCompany.id.toString();
			// Ensure company_id is set
			formData.company_id = cId;

			const res = isEdit
				? await customsBrokersApi.update(routeId!, formData)
				: await customsBrokersApi.create(formData, cId);

			if ((res as any).error) throw new Error((res as any).error);

			// UPSERT VU
			try {
				const vuRes = await customsBrokersApi.updateVU(formData.broker_key, vuData, cId);
				if ((vuRes as any).error) {
					toast.error(
						'Agente guardado, pero ocurrió un error guardando Ventanilla Única: ' +
							(vuRes as any).error
					);
					return; // Avoid triggering success redirection
				}
			} catch (vuErr: any) {
				toast.error('Agente guardado, pero ocurrió un error guardando Ventanilla Única.');
				console.error(vuErr);
				return;
			}

			toast.success(isEdit ? 'Agente actualizado' : 'Agente creado');
			goto('/dashboard/customs_brokers');
		} catch (e: any) {
			error = (e.message || 'Error al procesar la solicitud') as string;
			toast.error(error);
		} finally {
			loading = false;
		}
	}

	function handleCancel() {
		goto('/dashboard/customs_brokers');
	}

	useShortcuts(
		'Edit Broker Tabs',
		obtenerAtajosEdicionAgente({
			irGeneral: () => (activeTab = 'general'),
			irContacto: () => (activeTab = 'contact'),
			irDireccion: () => (activeTab = 'address'),
			irVU: () => (activeTab = 'vu'),
			guardar: handleSave,
			cancelar: handleCancel
		})
	);
</script>

<div class="space-y-3">
	<!-- Header -->
	<div class="flex items-center justify-between">
		<div class="space-y-1">
			<div class="flex items-center gap-3">
				<Button variant="ghost" size="icon" onclick={handleCancel}>
					<ArrowLeft size={20} />
				</Button>
				<h1 class="text-3xl font-bold tracking-tight">
					{isEdit ? `Agente ${formData.broker_key}` : 'Nuevo Agente Aduanal'}
				</h1>
				<Badge variant={isEdit ? 'outline' : 'default'}>
					{isEdit ? 'Edición' : 'Nuevo'}
				</Badge>
			</div>
			<p class="ml-12 text-muted-foreground">
				{isEdit
					? 'Modifica la información del agente aduanal'
					: 'Registra un nuevo agente aduanal en el sistema'}
			</p>
		</div>
	</div>

	<Separator />

	<!-- Main Content -->
	<div class="pb-48">
		<form
			onsubmit={(e) => {
				e.preventDefault();
				handleSave();
			}}
		>
			<Tabs.Root bind:value={activeTab}>
				<!-- Tab: General -->
				<Tabs.Content value="general">
					<Card.Root>
						<Card.Header>
							<Card.Title>Información General</Card.Title>
							<Card.Description>Identificación oficial del agente y patente.</Card.Description>
						</Card.Header>
						<Card.Content class="space-y-6">
							<div class="grid grid-cols-1 gap-6 md:grid-cols-2">
								<div class="grid gap-2">
									<Label>Tipo de Agente Aduanal</Label>
									<Select.Root
										type="single"
										value={formData.type || undefined}
										onValueChange={(v) => (formData.type = v)}
										disabled={loading}
									>
										<Select.Trigger class="h-10 w-full">
											{formData.type === 'MEX'
												? 'Agente Aduanal Mexicano'
												: formData.type === 'USA'
													? 'Agente Aduanal Americano (Broker)'
													: 'Selecciona un tipo...'}
										</Select.Trigger>
										<Select.Content>
											<Select.Item value="MEX">Agente Aduanal Mexicano</Select.Item>
											<Select.Item value="USA">Agente Aduanal Americano (Broker)</Select.Item>
										</Select.Content>
									</Select.Root>
								</div>
							</div>

							<div class="grid grid-cols-1 gap-6 md:grid-cols-2">
								<div class="grid gap-2">
									<Label class="required"
										>Clave Agente <span class="text-destructive">*</span></Label
									>
									<Input
										value={formData.broker_key}
										oninput={(e) => {
											const val = e.currentTarget.value.toUpperCase();
											if (val.length > 5) {
												brokerKeyError = true;
												formData.broker_key = val.slice(0, 5);
												e.currentTarget.value = formData.broker_key;

												clearTimeout(brokerKeyTimeout);
												brokerKeyTimeout = setTimeout(() => {
													brokerKeyError = false;
												}, 3000);
											} else {
												brokerKeyError = false;
												formData.broker_key = val;
											}
										}}
										placeholder="Ej. 550"
										maxlength={6}
										class={`h-10 ${brokerKeyError ? 'border-red-500 focus-visible:ring-red-500' : ''}`}
										disabled={isEdit || loading}
									/>
									{#if brokerKeyError}
										<p class="text-[0.8rem] font-medium text-destructive">
											La clave no debe superar los 5 caracteres
										</p>
									{/if}
								</div>
								<div class="grid gap-2">
									<Label class="required"
										>Patente / Autorización <span class="text-destructive">*</span></Label
									>
									<Input
										value={formData.license}
										oninput={(e) => {
											const val = e.currentTarget.value.replace(/\D/g, '');
											if (val.length > 4) {
												licenseError = true;
												formData.license = val.slice(0, 4);
												e.currentTarget.value = formData.license;

												clearTimeout(licenseTimeout);
												licenseTimeout = setTimeout(() => {
													licenseError = false;
												}, 3000);
											} else {
												licenseError = false;
												formData.license = val;
											}
										}}
										placeholder="Ej. 3421"
										maxlength={5}
										class={`h-10 ${licenseError ? 'border-red-500 focus-visible:ring-red-500' : ''}`}
										disabled={loading}
									/>
									{#if licenseError}
										<p class="text-[0.8rem] font-medium text-destructive">
											La patente no debe superar los 4 dígitos
										</p>
									{/if}
								</div>
							</div>

							<Separator />

							<div class="grid gap-2">
								<Label>Nombre / Razón Social</Label>
								<Input
									bind:value={formData.name}
									placeholder="Nombre oficial"
									disabled={loading}
									class="h-10"
								/>
							</div>

							<div class="grid grid-cols-1 gap-6 md:grid-cols-2">
								<div class="grid gap-2">
									<Label>RFC</Label>
									<Input
										bind:value={formData.tax_id}
										placeholder="RFC de la empresa"
										disabled={loading}
										class="h-10"
									/>
								</div>
								<div class="grid gap-2">
									<Label>CURP</Label>
									<Input
										bind:value={formData.personal_id}
										placeholder="CURP si aplica"
										disabled={loading}
										class="h-10"
									/>
								</div>
							</div>
						</Card.Content>
					</Card.Root>
				</Tabs.Content>

				<!-- Tab: Contact -->
				<Tabs.Content value="contact">
					<Card.Root>
						<Card.Header>
							<Card.Title>Información de Contacto</Card.Title>
							<Card.Description>Datos para comunicación con el agente.</Card.Description>
						</Card.Header>
						<Card.Content class="space-y-6">
							<div class="grid grid-cols-1 gap-6 md:grid-cols-2">
								<div class="grid gap-2">
									<Label>Persona de Contacto</Label>
									<Input
										bind:value={formData.contact}
										placeholder="Nombre del contacto"
										disabled={loading}
										class="h-10"
									/>
								</div>
								<div class="grid gap-2">
									<Label>Puesto / Cargo</Label>
									<Input
										bind:value={formData.position}
										placeholder="Ej. Gerente Comercial"
										disabled={loading}
										class="h-10"
									/>
								</div>
							</div>

							<Separator />

							<div class="grid grid-cols-1 gap-6 md:grid-cols-3">
								<div class="grid gap-2">
									<Label>Teléfono</Label>
									<Input
										bind:value={formData.phone}
										placeholder="656-000-0000"
										disabled={loading}
										class="h-10"
									/>
								</div>
								<div class="grid gap-2">
									<Label>Fax</Label>
									<Input bind:value={formData.fax} disabled={loading} class="h-10" />
								</div>
								<div class="grid gap-2">
									<Label>Correo Electrónico</Label>
									<Input
										type="email"
										bind:value={formData.email}
										placeholder="correo@empresa.com"
										disabled={loading}
										class="h-10"
									/>
								</div>
							</div>
						</Card.Content>
					</Card.Root>
				</Tabs.Content>

				<!-- Tab: Address -->
				<Tabs.Content value="address">
					<Card.Root>
						<Card.Header>
							<Card.Title>Domicilio Fiscal</Card.Title>
							<Card.Description>Ubicación registrada del agente aduanal.</Card.Description>
						</Card.Header>
						<Card.Content class="space-y-6">
							<div class="grid gap-2">
								<Label>Calle y Número</Label>
								<Input
									bind:value={formData.address}
									placeholder="Dirección completa"
									disabled={loading}
									class="h-10"
								/>
							</div>
							<div class="grid grid-cols-1 gap-6 md:grid-cols-3">
								<div class="grid gap-2">
									<Label>C.P.</Label>
									<Input
										bind:value={formData.postal_code}
										placeholder="32000"
										disabled={loading}
										class="h-10"
									/>
								</div>
								<div class="grid gap-2 md:col-span-2">
									<Label>Ciudad</Label>
									<Input
										bind:value={formData.city}
										placeholder="Ciudad"
										disabled={loading}
										class="h-10"
									/>
								</div>
							</div>
							<div class="grid grid-cols-1 gap-6 md:grid-cols-2">
								<div class="grid gap-2">
									<Label>Estado</Label>
									<div class="flex gap-1">
										<Input
											value={formData.state}
											readonly
											placeholder="Estado"
											disabled={loading}
											class="h-10 flex-1 cursor-pointer bg-muted"
											onclick={() => (showStateDialog = true)}
										/>
										<Button
											variant="outline"
											size="icon"
											class="h-10 w-10 shrink-0"
											onclick={() => (showStateDialog = true)}
											disabled={loading}
										>
											<MapPin class="h-4 w-4" />
										</Button>
									</div>
								</div>
								<div class="grid gap-2">
									<Label>País</Label>
									<div class="flex gap-1">
										<Input
											value={formData.country}
											readonly
											placeholder="MEX"
											disabled={loading}
											class="h-10 flex-1 cursor-pointer bg-muted"
											onclick={() => (showCountryDialog = true)}
										/>
										<Button
											variant="outline"
											size="icon"
											class="h-10 w-10 shrink-0"
											onclick={() => (showCountryDialog = true)}
											disabled={loading}
										>
											<Globe class="h-4 w-4" />
										</Button>
									</div>
								</div>
							</div>
						</Card.Content>
					</Card.Root>
					<CountryDialog bind:open={showCountryDialog} onSelect={handleCountrySelect} />
					<StateDialog
						bind:open={showStateDialog}
						onSelect={handleStateSelect}
						countryCode={formData.country ?? undefined}
					/>
				</Tabs.Content>
				<!-- Tab: Ventanilla Unica -->
				<Tabs.Content value="vu">
					<Card.Root>
						<Card.Header>
							<Card.Title>Ventanilla Única / Web Services</Card.Title>
							<Card.Description
								>Certificados y credenciales para integración con DODA/PITA.</Card.Description
							>
						</Card.Header>
						<Card.Content class="space-y-6">
							<div class="grid grid-cols-1 gap-6 md:grid-cols-2">
								<div class="grid gap-2">
									<Label
										>Ruta de archivo .cer <FileKey
											size={14}
											class="ml-1 inline text-muted-foreground"
										/></Label
									>
									<div class="flex items-center gap-2">
										<Input
											bind:value={vuData.certificate_path}
											placeholder="/ruta/certificados/agente.cer"
											disabled={loading}
											class="h-10 flex-1"
										/>
										<input
											type="file"
											class="hidden"
											onchange={(e) => handleLocalFileSelect(e, 'certificate_path')}
											id="vu-cert-file"
										/>
										<Button
											type="button"
											variant="outline"
											size="icon"
											class="h-10 w-10 shrink-0"
											disabled={loading}
											onclick={() => document.getElementById('vu-cert-file')?.click()}
										>
											<Folder class="h-4 w-4" />
										</Button>
									</div>
								</div>
								<div class="grid gap-2">
									<Label
										>Ruta de archivo .key <FileKey
											size={14}
											class="ml-1 inline text-muted-foreground"
										/></Label
									>
									<div class="flex items-center gap-2">
										<Input
											bind:value={vuData.key_path}
											placeholder="/ruta/certificados/agente.key"
											disabled={loading}
											class="h-10 flex-1"
										/>
										<input
											type="file"
											class="hidden"
											onchange={(e) => handleLocalFileSelect(e, 'key_path')}
											id="vu-key-file"
										/>
										<Button
											type="button"
											variant="outline"
											size="icon"
											class="h-10 w-10 shrink-0"
											disabled={loading}
											onclick={() => document.getElementById('vu-key-file')?.click()}
										>
											<Folder class="h-4 w-4" />
										</Button>
									</div>
								</div>
							</div>

							<div class="grid grid-cols-1 gap-6 md:grid-cols-2">
								<div class="grid gap-2">
									<Label
										>Clave acceso (FIEL) <Key
											size={14}
											class="ml-1 inline text-muted-foreground"
										/></Label
									>
									<Input
										type="password"
										bind:value={vuData.fiel_access_key}
										placeholder="********"
										disabled={loading}
										class="h-10"
									/>
								</div>
								<div class="grid gap-2">
									<Label
										>Tipo figura VU <ShieldCheck
											size={14}
											class="ml-1 inline text-muted-foreground"
										/></Label
									>
									<Select.Root type="single" bind:value={vuData.vu_figure_type} disabled={loading}>
										<Select.Trigger class="h-10">
											{vuData.vu_figure_type || 'Seleccionar tipo de figura'}
										</Select.Trigger>
										<Select.Content>
											<Select.Item value="AGENTE ADUANAL">AGENTE ADUANAL</Select.Item>
											<Select.Item value="APODERADO ADUANAL">APODERADO ADUANAL</Select.Item>
											<Select.Item value="MANDATARIO">MANDATARIO</Select.Item>
										</Select.Content>
									</Select.Root>
								</div>
							</div>

							<div class="grid grid-cols-1 gap-6 md:grid-cols-2">
								<div class="grid gap-2">
									<Label
										>Correo electrónico <Mail
											size={14}
											class="ml-1 inline text-muted-foreground"
										/></Label
									>
									<Input
										type="email"
										bind:value={vuData.vu_email}
										placeholder="agente@ejemplo.com"
										disabled={loading}
										class="h-10"
									/>
								</div>
								<div class="grid gap-2">
									<Label
										>R.F.C de consulta <Hash
											size={14}
											class="ml-1 inline text-muted-foreground"
										/></Label
									>
									<Input
										bind:value={vuData.query_tax_id}
										placeholder="RFC123456789"
										disabled={loading}
										class="h-10"
									/>
								</div>
							</div>

							<div class="grid grid-cols-1 gap-6 md:grid-cols-2">
								<div class="grid gap-2">
									<Label
										>Guardar archivos COVE <FileText
											size={14}
											class="ml-1 inline text-muted-foreground"
										/></Label
									>
									<div class="flex items-center gap-2">
										<Input
											bind:value={vuData.xml_files_path}
											placeholder="/ruta/cove/"
											disabled={loading}
											class="h-10 flex-1"
										/>
										<input
											type="file"
											class="hidden"
											onchange={(e) => handleLocalFileSelect(e, 'xml_files_path')}
											id="vu-cove-file"
										/>
										<Button
											type="button"
											variant="outline"
											size="icon"
											class="h-10 w-10 shrink-0"
											disabled={loading}
											onclick={() => document.getElementById('vu-cove-file')?.click()}
										>
											<Folder class="h-4 w-4" />
										</Button>
									</div>
								</div>
							</div>

							<Separator />

							<div class="grid grid-cols-1 gap-4 rounded-lg border bg-muted/30 p-4">
								<h3 class="text-xs font-bold tracking-wider text-muted-foreground uppercase">
									Configuración Adicional
								</h3>
								<div class="grid grid-cols-1 gap-6 md:grid-cols-2">
									<div class="grid gap-2">
										<Label>Formato FIEL</Label>
										<Input
											bind:value={vuData.fiel_format}
											placeholder="Ej: PKCS#12"
											disabled={loading}
											class="h-10"
										/>
									</div>
									<div class="grid gap-2">
										<Label>Clave Acceso Adicional</Label>
										<Input
											type="password"
											bind:value={vuData.access_key}
											placeholder="********"
											disabled={loading}
											class="h-10"
										/>
									</div>
									<div class="grid gap-2">
										<Label>Ruta Lectura Firma</Label>
										<Input
											bind:value={vuData.signature_read_path}
											placeholder="/ruta/lectura/firma"
											disabled={loading}
											class="h-10"
										/>
									</div>
									<div class="grid gap-2">
										<Label>Ruta Archivo Respaldo</Label>
										<Input
											bind:value={vuData.archive_path}
											placeholder="/ruta/respaldo/"
											disabled={loading}
											class="h-10"
										/>
									</div>
								</div>
							</div>
						</Card.Content>
					</Card.Root>
				</Tabs.Content>

				<!-- Tab: DODA -->
				<Tabs.Content value="doda">
					<Card.Root>
						<Card.Header>
							<Card.Title>DODA-PITA</Card.Title>
							<Card.Description>Configuración de servicios DODA / PITA.</Card.Description>
						</Card.Header>
						<Card.Content class="space-y-6">
							<div class="grid grid-cols-1 gap-6 md:grid-cols-2">
								<div class="grid gap-2">
									<Label>Usuario <User size={14} class="ml-1 inline text-muted-foreground" /></Label
									>
									<Input
										bind:value={vuData.doda_web_service_user}
										placeholder="Usuario Web Service"
										disabled={loading}
										class="h-10"
									/>
								</div>
								<div class="grid gap-2">
									<Label
										>Clave de acceso <Key
											size={14}
											class="ml-1 inline text-muted-foreground"
										/></Label
									>
									<Input
										type="password"
										bind:value={vuData.doda_web_service_access_key}
										placeholder="Contraseña WS"
										disabled={loading}
										class="h-10"
									/>
								</div>
							</div>

							<div class="grid grid-cols-1 gap-6 md:grid-cols-2">
								<div class="grid gap-2">
									<Label
										>Ruta archivo .cer <FileKey
											size={14}
											class="ml-1 inline text-muted-foreground"
										/></Label
									>
									<div class="flex items-center gap-2">
										<Input
											bind:value={vuData.doda_certificate_path}
											placeholder="/ruta/certificados/doda.cer"
											disabled={loading}
											class="h-10 flex-1"
										/>
										<input
											type="file"
											class="hidden"
											onchange={(e) => handleLocalFileSelect(e, 'doda_certificate_path')}
											id="doda-cert-file"
										/>
										<Button
											type="button"
											variant="outline"
											size="icon"
											class="h-10 w-10 shrink-0"
											disabled={loading}
											onclick={() => document.getElementById('doda-cert-file')?.click()}
										>
											<Folder class="h-4 w-4" />
										</Button>
									</div>
								</div>
								<div class="grid gap-2">
									<Label
										>Ruta archivo .key <FileKey
											size={14}
											class="ml-1 inline text-muted-foreground"
										/></Label
									>
									<div class="flex items-center gap-2">
										<Input
											bind:value={vuData.doda_key_path}
											placeholder="/ruta/certificados/doda.key"
											disabled={loading}
											class="h-10 flex-1"
										/>
										<input
											type="file"
											class="hidden"
											onchange={(e) => handleLocalFileSelect(e, 'doda_key_path')}
											id="doda-key-file"
										/>
										<Button
											type="button"
											variant="outline"
											size="icon"
											class="h-10 w-10 shrink-0"
											disabled={loading}
											onclick={() => document.getElementById('doda-key-file')?.click()}
										>
											<Folder class="h-4 w-4" />
										</Button>
									</div>
								</div>
							</div>

							<div class="grid grid-cols-1 gap-6 md:grid-cols-2">
								<div class="grid gap-2">
									<Label
										>Clave acceso .key <Key
											size={14}
											class="ml-1 inline text-muted-foreground"
										/></Label
									>
									<Input
										type="password"
										bind:value={vuData.doda_fiel_access_key}
										placeholder="********"
										disabled={loading}
										class="h-10"
									/>
								</div>
								<div class="grid gap-2">
									<Label
										>Guardar archivos DODA-XML, en: <FileText
											size={14}
											class="ml-1 inline text-muted-foreground"
										/></Label
									>
									<div class="flex items-center gap-2">
										<Input
											bind:value={vuData.doda_xml_files_path}
											placeholder="/ruta/doda-xml/"
											disabled={loading}
											class="h-10 flex-1"
										/>
										<input
											type="file"
											class="hidden"
											onchange={(e) => handleLocalFileSelect(e, 'doda_xml_files_path')}
											id="doda-xml-file"
										/>
										<Button
											type="button"
											variant="outline"
											size="icon"
											class="h-10 w-10 shrink-0"
											disabled={loading}
											onclick={() => document.getElementById('doda-xml-file')?.click()}
										>
											<Folder class="h-4 w-4" />
										</Button>
									</div>
								</div>
							</div>
						</Card.Content>
					</Card.Root>
				</Tabs.Content>
				<Tabs.Content value="anam">
					<Card.Root>
						<Card.Header>
							<Card.Title>ANAM</Card.Title>
							<Card.Description>Configuración de acceso para ANAM.</Card.Description>
						</Card.Header>
						<Card.Content class="space-y-6">
							<div class="grid grid-cols-1 gap-6 md:grid-cols-2">
								<div class="grid gap-2">
									<Label>Usuario <User size={14} class="ml-1 inline text-muted-foreground" /></Label
									>
									<Input
										bind:value={vuData.web_service_user}
										placeholder="Usuario ANAM"
										disabled={loading}
										class="h-10"
									/>
								</div>
								<div class="grid gap-2">
									<Label
										>Clave acceso <Lock
											size={14}
											class="ml-1 inline text-muted-foreground"
										/></Label
									>
									<Input
										type="password"
										bind:value={vuData.web_service_access_key}
										placeholder="********"
										disabled={loading}
										class="h-10"
									/>
								</div>
							</div>
						</Card.Content>
					</Card.Root>
				</Tabs.Content>
			</Tabs.Root>
		</form>
	</div>
</div>

<!-- Sticky Footer -->
<div
	class="fixed right-0 bottom-0 left-0 z-[5] ml-[calc(var(--sidebar-width))] border-t bg-background/95 shadow-lg backdrop-blur group-has-data-[state=collapsed]/sidebar-wrapper:ml-[calc(var(--sidebar-width-icon))] supports-[backdrop-filter]:bg-background/80"
>
	<div class="mx-auto max-w-[1400px] space-y-4 px-4 py-4">
		<!-- Footer Navigation -->
		<Tabs.Root bind:value={activeTab}>
			<div class="w-full overflow-x-auto pb-2">
				<Tabs.List class="grid w-full grid-cols-6">
					<Tabs.Trigger value="general">General</Tabs.Trigger>
					<Tabs.Trigger value="contact">Contacto</Tabs.Trigger>
					<Tabs.Trigger value="address">Domicilio</Tabs.Trigger>
					<Tabs.Trigger value="vu">VU</Tabs.Trigger>
					<Tabs.Trigger value="doda">DODA</Tabs.Trigger>
					<Tabs.Trigger value="anam">ANAM</Tabs.Trigger>
				</Tabs.List>
			</div>
		</Tabs.Root>

		<!-- Actions -->
		<div class="flex justify-end gap-3">
			<Button variant="outline" onclick={handleCancel} disabled={loading}>Cancelar</Button>
			<Button onclick={handleSave} disabled={loading}>
				{#if loading}
					<Loader2 class="mr-2 h-4 w-4 animate-spin" />
					Guardando...
				{:else}
					<Save size={16} class="mr-2" />
					{isEdit ? 'Actualizar Agente' : 'Guardar Agente'}
				{/if}
			</Button>
		</div>
	</div>
</div>
