<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: '',
		personal_id: '',
		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 || '',
				personal_id: initialData.personal_id || '',
				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: '',
				personal_id: '',
				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;
			}
			if (
				formData.license === '0' ||
				formData.license === '0000' ||
				/^0+$/.test(formData.license)
			) {
				toast.error('La Patente no puede ser 0');
				loading = false;
				return;
			}
			if (formData.tax_id && !/^[A-Z&Ñ]{3,4}\d{6}[A-Z0-9]{3}$/i.test(formData.tax_id)) {
				toast.error('El formato del RFC es inválido');
				loading = false;
				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
				)
			) {
				toast.error('El formato de la CURP es inválido');
				loading = false;
				return;
			}
			if (
				formData.email &&
				!/^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/.test(formData.email)
			) {
				toast.error('El formato del correo electrónico es inválido');
				loading = false;
				return;
			}
			if (formData.phone && !/^[\d\s\-\+\(\)]+$/.test(formData.phone)) {
				toast.error('El teléfono contiene caracteres no válidos');
				loading = false;
				return;
			}
			if (formData.fax && !/^[\d\s\-\+\(\)]+$/.test(formData.fax)) {
				toast.error('El fax contiene caracteres no válidos');
				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: unknown) {
			console.error(error);
			// Intentar extraer el mensaje del servidor si lo hay
			let msg = 'Error al guardar el agente aduanal';
			if (error && typeof error === 'object' && 'message' in error) {
				msg = (error as { message: string }).message || msg;
			}
			toast.error(msg);
		} finally {
			loading = false;
		}
	}
</script>

<Dialog.Root bind:open>
	<Dialog.Content class="max-h-[90vh] overflow-y-auto sm:max-w-[700px]">
		<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 leading-none font-medium 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().replace(/[^A-Z0-9]/g, '');
								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;
									e.currentTarget.value = formData.broker_key;
								}
							}}
							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="col-span-2 space-y-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"
							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 agencia"
							maxlength={13}
							disabled={loading}
						/>
					</div>
					<div class="space-y-2">
						<Label for="personal_id">CURP</Label>
						<Input
							id="personal_id"
							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 (Opcional)"
							maxlength={18}
							disabled={loading}
						/>
					</div>
					<div class="col-span-2 space-y-2">
						<Label for="contact">Nombre Contacto</Label>
						<Input
							id="contact"
							value={formData.contact}
							oninput={(e) => {
								formData.contact = e.currentTarget.value.replace(
									/[^a-zA-Z0-9\sñÑáéíóúÁÉÍÓÚ\-\.,]/g,
									''
								);
								e.currentTarget.value = formData.contact;
							}}
							placeholder="Persona de contacto"
							disabled={loading}
						/>
					</div>
				</div>
			</div>

			<Separator />

			<div class="space-y-4">
				<h4 class="text-sm leading-none font-medium text-muted-foreground">Contacto</h4>
				<div class="grid grid-cols-3 gap-4">
					<div class="col-span-1 space-y-2">
						<Label for="phone">Teléfono</Label>
						<Input
							id="phone"
							value={formData.phone}
							oninput={(e) => {
								formData.phone = e.currentTarget.value.replace(/[^\d\s\-\+\(\)]/g, '');
								e.currentTarget.value = formData.phone;
							}}
							disabled={loading}
						/>
					</div>
					<div class="col-span-1 space-y-2">
						<Label for="fax">Fax</Label>
						<Input
							id="fax"
							value={formData.fax}
							oninput={(e) => {
								formData.fax = e.currentTarget.value.replace(/[^\d\s\-\+\(\)]/g, '');
								e.currentTarget.value = formData.fax;
							}}
							disabled={loading}
						/>
					</div>
					<div class="col-span-1 space-y-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 leading-none font-medium 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}
							oninput={(e) => {
								formData.postal_code = e.currentTarget.value.replace(/[^a-zA-Z0-9]/g, '');
							}}
						/>
					</div>
					<div class="col-span-2 space-y-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>
