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

	// 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, FilePickerInput } 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,
		Mail,
		UserRound,
		Fingerprint,
		Lock,
		Signature,
		Archive,
		ShieldCheck
	} from 'lucide-svelte';
	import { toast } from 'svelte-sonner';
	import { getFileDisplayName } from '$lib/utils';
	import { useShortcuts } from '$lib/hooks/use-shortcuts';
	import { obtenerAtajosEdicionAgente } from '$lib/config/shortcuts/dashboard/customs_brokers/edit';
	import ErrorState from '$lib/components/dashboard/common/error-state.svelte';

	// --- 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');
	const canAccessBrokerEditor = $derived(
		isEdit ? canEditCustomsBrokers($currentUser) : canCreateCustomsBrokers($currentUser)
	);

	// --- 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 pendingVuFiles = $state<{
		certificate?: File;
		key?: File;
		cove?: File;
		dodaCertificate?: File;
		dodaKey?: File;
		dodaCove?: File;
	}>({});

	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 ---
	async function uploadPendingVuFiles(companyId: string, brokerKey: string) {
		if (pendingVuFiles.certificate) {
			const res = await uploadCustomsBrokerVuFile(
				brokerKey,
				companyId,
				'certificate',
				pendingVuFiles.certificate
			);
			if ((res as any).error || !(res as any).data?.path) {
				throw new Error((res as any).error || 'Error al subir certificado VU (.cer)');
			}
			vuData.certificate_path = (res as any).data.path;
		}

		if (pendingVuFiles.key) {
			const res = await uploadCustomsBrokerVuFile(brokerKey, companyId, 'key', pendingVuFiles.key);
			if ((res as any).error || !(res as any).data?.path) {
				throw new Error((res as any).error || 'Error al subir llave VU (.key)');
			}
			vuData.key_path = (res as any).data.path;
		}

		if (pendingVuFiles.cove) {
			const res = await uploadCustomsBrokerVuFile(brokerKey, companyId, 'cove', pendingVuFiles.cove);
			if ((res as any).error || !(res as any).data?.path) {
				throw new Error((res as any).error || 'Error al subir archivo COVE');
			}
			vuData.xml_files_path = (res as any).data.path;
		}

		if (pendingVuFiles.dodaCertificate) {
			const res = await uploadCustomsBrokerVuFile(
				brokerKey,
				companyId,
				'doda_certificate',
				pendingVuFiles.dodaCertificate
			);
			if ((res as any).error || !(res as any).data?.path) {
				throw new Error((res as any).error || 'Error al subir certificado DODA (.cer)');
			}
			vuData.doda_certificate_path = (res as any).data.path;
		}

		if (pendingVuFiles.dodaKey) {
			const res = await uploadCustomsBrokerVuFile(
				brokerKey,
				companyId,
				'doda_key',
				pendingVuFiles.dodaKey
			);
			if ((res as any).error || !(res as any).data?.path) {
				throw new Error((res as any).error || 'Error al subir llave DODA (.key)');
			}
			vuData.doda_key_path = (res as any).data.path;
		}

		if (pendingVuFiles.dodaCove) {
			const res = await uploadCustomsBrokerVuFile(
				brokerKey,
				companyId,
				'doda_cove',
				pendingVuFiles.dodaCove
			);
			if ((res as any).error || !(res as any).data?.path) {
				throw new Error((res as any).error || 'Error al subir archivo DODA');
			}
			vuData.doda_xml_files_path = (res as any).data.path;
		}

		pendingVuFiles = {};
	}

	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) {
		// Mostrar en Estado la clave del estado (mex_key/ame_key), no el país (m3_key)
		formData.state = state.mex_key || state.ame_key || state.m3_key;
		if (state.m3_key) formData.country = state.m3_key;
	}

	// --- 4. GUARDADO ---
	async function handleSave() {
		if (!canAccessBrokerEditor) {
			toast.error('No tienes permiso para guardar agentes aduanales');
			return;
		}
		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;
		}

		if (formData.license === '0' || formData.license === '0000' || /^0+$/.test(formData.license)) {
			error = 'La Patente no puede ser 0';
			toast.error(error);
			return;
		}

		if (formData.tax_id && !/^[A-Z&Ñ]{3,4}\d{6}[A-Z0-9]{3}$/i.test(formData.tax_id)) {
			error = 'El formato del RFC es inválido';
			toast.error(error);
			return;
		}

		if (
			formData.personal_id &&
			!/^[A-Z][AEIOUX][A-Z]{2}\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])[HM](AS|BC|BS|CC|CS|CH|CL|CM|DF|DG|GT|GR|HG|JC|MC|MN|MS|NT|NL|OC|PL|QT|QR|SP|SL|SR|TC|TS|TL|VZ|YN|ZS|NE)[B-DF-HJ-NP-TV-Z]{3}[0-9A-Z]\d$/i.test(
				formData.personal_id
			)
		) {
			error = 'El formato de la CURP es inválido';
			toast.error(error);
			return;
		}

		if (
			formData.email &&
			!/^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/.test(formData.email)
		) {
			error = 'El formato del correo electrónico es inválido';
			toast.error(error);
			return;
		}

		if (formData.phone && !/^[\d\s\-\+\(\)]+$/.test(formData.phone)) {
			error = 'El teléfono contiene caracteres no válidos';
			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);

			// Primero sube archivos CER/KEY/COVE al bucket y guarda la ruta real en vuData.
			await uploadPendingVuFiles(cId, formData.broker_key);

			// 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');
	}

	function openOnEnterOrSpace(event: KeyboardEvent, openDialog: () => void) {
		if (event.key === 'Enter' || event.key === ' ') {
			event.preventDefault();
			openDialog();
		}
	}

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

{#if !canAccessBrokerEditor}
	<div
		class="flex h-[calc(100svh-4rem)] flex-col p-6 group-has-data-[collapsible=icon]/sidebar-wrapper:h-[calc(100svh-3rem)]"
	>
		<ErrorState status={403} />
	</div>
{:else}
<Tabs.Root bind:value={activeTab}>
	<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();
			}}
		>
			<!-- 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
										value={formData.tax_id}
										oninput={(e) => {
											formData.tax_id = e.currentTarget.value
												.toUpperCase()
												.replace(/[^A-Z0-9&Ñ]/g, '')
												.slice(0, 13);
											e.currentTarget.value = formData.tax_id;
										}}
										placeholder="RFC de la empresa"
										disabled={loading}
										class="h-10"
									/>
								</div>
								<div class="grid gap-2">
									<Label>CURP</Label>
									<Input
										value={formData.personal_id}
										oninput={(e) => {
											formData.personal_id = e.currentTarget.value
												.toUpperCase()
												.replace(/[^A-Z0-9]/g, '')
												.slice(0, 18);
											e.currentTarget.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
										value={formData.contact}
										oninput={(e) => {
											formData.contact = e.currentTarget.value.replace(
												/[^a-zA-Z0-9\sñÑáéíóúÁÉÍÓÚ\-\.,]/g,
												''
											);
											e.currentTarget.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
										value={formData.phone}
										oninput={(e) => {
											formData.phone = e.currentTarget.value.replace(/[^\d\s\-\+\(\)]/g, '');
											e.currentTarget.value = formData.phone;
										}}
										placeholder="656-000-0000"
										disabled={loading}
										class="h-10"
									/>
								</div>
								<div class="grid gap-2">
									<Label>Fax</Label>
									<Input
										value={formData.fax}
										oninput={(e) => {
											formData.fax = e.currentTarget.value.replace(/[^\d\s\-\+\(\)]/g, '');
											e.currentTarget.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"
										oninput={(e) => {
											formData.postal_code = e.currentTarget.value.replace(/[^a-zA-Z0-9]/g, '');
										}}
									/>
								</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"
											tabindex={loading ? -1 : 0}
											onclick={() => (showStateDialog = true)}
											onkeydown={(event) =>
												openOnEnterOrSpace(event, () => (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"
											tabindex={loading ? -1 : 0}
											onclick={() => (showCountryDialog = true)}
											onkeydown={(event) =>
												openOnEnterOrSpace(event, () => (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
										>Archivo .cer <FileKey
											size={14}
											class="ml-1 inline text-muted-foreground"
										/></Label
									>
									<FilePickerInput
										value={getFileDisplayName(vuData.certificate_path, 'CER', 'Seleccionar archivo .cer')}
										placeholder="Seleccionar archivo .cer"
										accept=".cer"
										disabled={loading}
										onchange={(file) => {
											vuData.certificate_path = file.name;
											pendingVuFiles.certificate = file;
											toast.success(`Archivo ${file.name} seleccionado`);
										}}
									/>
								</div>
								<div class="grid gap-2">
									<Label
										>Archivo .key <FileKey
											size={14}
											class="ml-1 inline text-muted-foreground"
										/></Label
									>
									<FilePickerInput
										value={getFileDisplayName(vuData.key_path, 'KEY', 'Seleccionar archivo .key')}
										placeholder="Seleccionar archivo .key"
										accept=".key"
										disabled={loading}
										onchange={(file) => {
											vuData.key_path = file.name;
											pendingVuFiles.key = file;
											toast.success(`Archivo ${file.name} seleccionado`);
										}}
									/>
								</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 w-full">
											{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
										>Usuario Web Service VU <User
											size={14}
											class="ml-1 inline text-muted-foreground"
										/></Label
									>
									<Input
										bind:value={vuData.web_service_user}
										placeholder="Usuario VU"
										disabled={loading}
										class="h-10"
									/>
								</div>
								<div class="grid gap-2">
									<Label
										>Clave Web Service VU <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>

							<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
									>
									<FilePickerInput
										value={getFileDisplayName(vuData.xml_files_path, 'COVE', 'Seleccionar archivo COVE')}
										placeholder="Seleccionar archivo COVE"
										disabled={loading}
										onchange={(file) => {
											vuData.xml_files_path = file.name;
											pendingVuFiles.cove = file;
											toast.success(`Archivo ${file.name} seleccionado`);
										}}
									/>
								</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
										>Archivo .cer <FileKey
											size={14}
											class="ml-1 inline text-muted-foreground"
										/></Label
									>
									<FilePickerInput
										value={getFileDisplayName(vuData.doda_certificate_path, 'CER', 'Seleccionar archivo .cer')}
										placeholder="Seleccionar archivo .cer"
										accept=".cer"
										disabled={loading}
										onchange={(file) => {
											vuData.doda_certificate_path = file.name;
											pendingVuFiles.dodaCertificate = file;
											toast.success(`Archivo ${file.name} seleccionado`);
										}}
									/>
								</div>
								<div class="grid gap-2">
									<Label
										>Archivo .key <FileKey
											size={14}
											class="ml-1 inline text-muted-foreground"
										/></Label
									>
									<FilePickerInput
										value={getFileDisplayName(vuData.doda_key_path, 'KEY', 'Seleccionar archivo .key')}
										placeholder="Seleccionar archivo .key"
										accept=".key"
										disabled={loading}
										onchange={(file) => {
											vuData.doda_key_path = file.name;
											pendingVuFiles.dodaKey = file;
											toast.success(`Archivo ${file.name} seleccionado`);
										}}
									/>
								</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
									>
									<FilePickerInput
										value={getFileDisplayName(vuData.doda_xml_files_path, 'XML', 'Seleccionar archivo XML')}
										placeholder="Seleccionar archivo XML"
										disabled={loading}
										onchange={(file) => {
											vuData.doda_xml_files_path = file.name;
											pendingVuFiles.dodaCove = file;
											toast.success(`Archivo ${file.name} seleccionado`);
										}}
									/>
								</div>
							</div>
						</Card.Content>
					</Card.Root>
				</Tabs.Content>
		</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 -->
			<div class="w-full overflow-x-auto pb-2">
			<Tabs.List class="grid w-full grid-cols-5">
				<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.List>
			</div>

			<!-- 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>
</Tabs.Root>
{/if}
