<script lang="ts">
	import { Button } from '$lib/components/ui/button';
	import * as Dialog from '$lib/components/ui/dialog';
	import { Input } from '$lib/components/ui/input';
	import { Label } from '$lib/components/ui/label';
	import { Separator } from '$lib/components/ui/separator';
	import { Loader2 } from 'lucide-svelte';
	import type {
		CreateCustomsBrokerData,
		CustomsBroker
	} from '$lib/api/dashboard/a76/customs-brokers'; // Ajusta la ruta
	import { toast } from 'svelte-sonner';

	// --- Props ---
	export let open = false;
	export let mode: 'create' | 'edit' = 'create';
	export let initialData: CustomsBroker | null = null;
	export let companyId: string; // Necesario según tu API

	// La función onSave ahora devuelve una promesa para manejar el loading aquí
	export let onSave: (data: CreateCustomsBrokerData) => Promise<void>;

	// --- Estado ---
	let loading = false;

	// Estado del formulario
	let formData: CreateCustomsBrokerData = {
		broker_key: '',
		license: '',
		name: '',
		tax_id: '',
		email: '',
		phone: '',
		fax: '',
		contact: '',
		address: '',
		postal_code: '',
		city: '',
		state: '',
		country: '',
		tenant_id: '', // Se llenará en el submit o por defecto
		company_id: ''
	};

	let brokerKeyError = false;
	let licenseError = false;
	let brokerKeyTimeout: ReturnType<typeof setTimeout>;
	let licenseTimeout: ReturnType<typeof setTimeout>;

	// --- Reactividad ---
	$: if (open) {
		if (mode === 'edit' && initialData) {
			// Cargar datos existentes
			formData = {
				...initialData,
				// Aseguramos que no sean null/undefined para los inputs
				name: initialData.name || '',
				tax_id: initialData.tax_id || '',
				email: initialData.email || '',
				phone: initialData.phone || '',
				fax: initialData.fax || '',
				contact: initialData.contact || '',
				address: initialData.address || '',
				postal_code: initialData.postal_code || '',
				city: initialData.city || '',
				state: initialData.state || '',
				country: initialData.country || '',
				license: initialData.license || ''
			};
		} else {
			// Reset para crear
			formData = {
				broker_key: '',
				license: '',
				name: '',
				tax_id: '',
				email: '',
				phone: '',
				fax: '',
				contact: '',
				address: '',
				postal_code: '',
				city: '',
				state: '',
				country: 'MEX', // Valor por defecto sugerido
				tenant_id: 'default', // Ajustar según lógica de tu app
				company_id: companyId
			};
		}
	}

	// --- Handlers ---
	async function handleSubmit() {
		try {
			loading = true;

			// Validaciones básicas
			if (!formData.broker_key) {
				toast.error('La Clave del Agente es obligatoria');
				loading = false;
				return;
			}
			if (!formData.license) {
				toast.error('La Patente es obligatoria');
				loading = false;
				return;
			}

			if (formData.broker_key.length > 5) {
				toast.error('La Clave del Agente no debe superar los 5 caracteres');
				loading = false;
				return;
			}
			if (formData.license && formData.license.length > 4) {
				toast.error('La Patente no debe superar los 4 dígitos');
				loading = false;
				return;
			}

			// Inyectar company_id si no viene
			const payload = { ...formData, company_id: companyId };

			await onSave(payload);
			open = false;
			toast.success(
				mode === 'create' ? 'Agente creado correctamente' : 'Agente actualizado correctamente'
			);
		} catch (error) {
			console.error(error);
			toast.error('Error al guardar el agente aduanal');
		} finally {
			loading = false;
		}
	}
</script>

<Dialog.Root bind:open>
	<Dialog.Content class="sm:max-w-[700px] max-h-[90vh] overflow-y-auto">
		<Dialog.Header>
			<Dialog.Title>
				{mode === 'create' ? 'Nuevo Agente Aduanal' : 'Editar Agente Aduanal'}
			</Dialog.Title>
			<Dialog.Description>
				Ingresa los datos generales del agente. La configuración de VU y Personal se gestiona
				aparte.
			</Dialog.Description>
		</Dialog.Header>

		<div class="grid gap-6 py-4">
			<div class="space-y-4">
				<h4 class="text-sm font-medium leading-none text-muted-foreground">Identificación</h4>
				<div class="grid grid-cols-2 gap-4">
					<div class="space-y-2">
						<Label for="broker_key">Clave Agente *</Label>
						<Input
							id="broker_key"
							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={brokerKeyError ? 'border-red-500 focus-visible:ring-red-500' : ''}
							disabled={mode === 'edit' || 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="space-y-2">
						<Label for="license">Patente *</Label>
						<Input
							id="license"
							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={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>
				<div class="grid grid-cols-2 gap-4">
					<div class="space-y-2 col-span-2">
						<Label for="name">Nombre / Razón Social</Label>
						<Input
							id="name"
							bind:value={formData.name}
							placeholder="Nombre del Agente o Agencia"
							disabled={loading}
						/>
					</div>
					<div class="space-y-2">
						<Label for="tax_id">RFC</Label>
						<Input
							id="tax_id"
							bind:value={formData.tax_id}
							placeholder="RFC de la agencia"
							disabled={loading}
						/>
					</div>
					<div class="space-y-2">
						<Label for="contact">Nombre Contacto</Label>
						<Input
							id="contact"
							bind:value={formData.contact}
							placeholder="Persona de contacto"
							disabled={loading}
						/>
					</div>
				</div>
			</div>

			<Separator />

			<div class="space-y-4">
				<h4 class="text-sm font-medium leading-none text-muted-foreground">Contacto</h4>
				<div class="grid grid-cols-3 gap-4">
					<div class="space-y-2 col-span-1">
						<Label for="phone">Teléfono</Label>
						<Input id="phone" bind:value={formData.phone} disabled={loading} />
					</div>
					<div class="space-y-2 col-span-2">
						<Label for="email">Correo Electrónico</Label>
						<Input id="email" type="email" bind:value={formData.email} disabled={loading} />
					</div>
				</div>
			</div>

			<Separator />

			<div class="space-y-4">
				<h4 class="text-sm font-medium leading-none text-muted-foreground">Dirección Fiscal</h4>

				<div class="space-y-2">
					<Label for="address">Calle y Número</Label>
					<Input id="address" bind:value={formData.address} disabled={loading} />
				</div>

				<div class="grid grid-cols-4 gap-4">
					<div class="space-y-2">
						<Label for="postal_code">C.P.</Label>
						<Input id="postal_code" bind:value={formData.postal_code} disabled={loading} />
					</div>
					<div class="space-y-2 col-span-2">
						<Label for="city">Ciudad</Label>
						<Input id="city" bind:value={formData.city} disabled={loading} />
					</div>
					<div class="space-y-2">
						<Label for="state">Estado</Label>
						<Input id="state" bind:value={formData.state} disabled={loading} />
					</div>
				</div>
				<div class="grid grid-cols-4 gap-4">
					<div class="space-y-2">
						<Label for="country">País</Label>
						<Input id="country" bind:value={formData.country} disabled={loading} />
					</div>
				</div>
			</div>
		</div>

		<Dialog.Footer>
			<Button variant="outline" onclick={() => (open = false)} disabled={loading}>Cancelar</Button>
			<Button onclick={handleSubmit} disabled={loading}>
				{#if loading}
					<Loader2 class="mr-2 h-4 w-4 animate-spin" />
					Guardando
				{:else}
					Guardar Agente
				{/if}
			</Button>
		</Dialog.Footer>
	</Dialog.Content>
</Dialog.Root>
