<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 {
		customsBrokersApi,
		type CreateCustomsBrokerData,
		type CustomsBroker
	} from '$lib/api/dashboard/a76/customs-brokers';
	import { companyStore } from '$lib/stores/company.svelte';

	let {
		open = $bindable(false),
		broker,
		onSuccess
	}: {
		open: boolean;
		broker: CustomsBroker;
		onSuccess?: () => void;
	} = $props();

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

	let loading = $state(false);
	let error = $state<string | null>(null);
	let licenseError = $state(false);
	let licenseTimeout: ReturnType<typeof setTimeout>;

	// Inicializar formulario cuando cambia el broker
	$effect(() => {
		if (open && broker) {
			formData = {
				name: broker.name || '',
				type: broker.type || '',
				address: broker.address || '',
				postal_code: broker.postal_code || '',
				city: broker.city || '',
				state: broker.state || '',
				phone: broker.phone || '',
				fax: broker.fax || '',
				email: broker.email || '',
				country: broker.country || '',
				tax_id: broker.tax_id || '',
				personal_id: broker.personal_id || '',
				position: broker.position || '',
				license: broker.license || '',
				company: broker.company || '',
				contact: broker.contact || ''
			};
		}
	});

	async function handleSubmit(e: Event) {
		e.preventDefault();

		if (!companyStore.activeCompany) {
			error = 'No hay compañía seleccionada';
			return;
		}

		loading = true;
		error = null;

		// Validaciones Básicas
		if (formData.license === '0' || formData.license === '0000' || /^0+$/.test(formData.license)) {
			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)) {
			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
			)
		) {
			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)
		) {
			error = 'El formato del correo electrónico es inválido';
			loading = false;
			return;
		}
		if (formData.phone && !/^[\d\s\-\+\(\)]+$/.test(formData.phone)) {
			error = 'El teléfono contiene caracteres no válidos';
			loading = false;
			return;
		}

		try {
			const payload: CreateCustomsBrokerData = {
				broker_key: broker.broker_key, // La clave no se edita
				name: formData.name || null,
				type: formData.type || null,
				address: formData.address || null,
				postal_code: formData.postal_code || null,
				city: formData.city || null,
				state: formData.state || null,
				phone: formData.phone || null,
				fax: formData.fax || null,
				email: formData.email || null,
				country: formData.country || null,
				tax_id: formData.tax_id || null,
				personal_id: formData.personal_id || null,
				position: formData.position || null,
				license: formData.license || null,
				company: formData.company || null,
				contact: formData.contact || null,
				tenant_id: broker.tenant_id,
				company_id: companyStore.activeCompany.id.toString()
			};

			const response = await customsBrokersApi.update(broker.broker_key, payload);

			if (response.error) {
				if (response.status === 401) {
					error = 'Sesión expirada. Recargando página...';
					setTimeout(() => {
						window.location.reload();
					}, 1500);
				} else {
					error = response.error;
				}
				return;
			}

			// Éxito
			open = false;
			if (onSuccess) {
				onSuccess();
			}
		} catch (e) {
			error = e instanceof Error ? e.message : 'Error al guardar';
			console.error('Error updating:', e);
		} finally {
			loading = false;
		}
	}

	function handleOpenChange(newOpen: boolean) {
		open = newOpen;
		if (!newOpen) {
			error = null;
		}
	}
</script>

<Dialog.Root bind:open onOpenChange={handleOpenChange}>
	<Dialog.Content class="max-h-[90vh] overflow-y-auto sm:max-w-[700px]">
		<Dialog.Header>
			<Dialog.Title>Editar Agente Aduanal</Dialog.Title>
			<Dialog.Description>
				Modifica los datos del agente aduanal <span class="font-mono font-semibold"
					>{broker?.broker_key}</span
				>.
			</Dialog.Description>
		</Dialog.Header>

		<form onsubmit={handleSubmit} class="space-y-6">
			{#if error}
				<div
					class="rounded-lg border border-destructive bg-destructive/10 p-3 text-sm text-destructive"
				>
					{error}
				</div>
			{/if}

			<!-- Información básica -->
			<div class="space-y-4">
				<h3 class="text-sm font-semibold">Información Básica</h3>

				<div class="grid grid-cols-2 gap-4">
					<div class="space-y-2">
						<Label for="edit-broker_key">Clave</Label>
						<Input
							id="edit-broker_key"
							value={broker?.broker_key}
							disabled
							class="bg-muted {broker?.broker_key?.length > 5 ? 'border-red-500' : ''}"
						/>
					</div>

					<div class="space-y-2">
						<Label for="edit-type">Tipo</Label>
						<Input
							id="edit-type"
							bind:value={formData.type}
							placeholder="Tipo de agente"
							maxlength={9}
							disabled={loading}
						/>
					</div>
				</div>

				<div class="space-y-2">
					<Label for="edit-name">Nombre</Label>
					<Input
						id="edit-name"
						bind:value={formData.name}
						placeholder="Nombre del agente aduanal"
						maxlength={80}
						disabled={loading}
					/>
				</div>

				<div class="grid grid-cols-2 gap-4">
					<div class="space-y-2">
						<Label for="edit-license">Patente</Label>
						<Input
							id="edit-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="Número de patente"
							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 class="space-y-2">
						<Label for="edit-company">Empresa</Label>
						<Input
							id="edit-company"
							bind:value={formData.company}
							placeholder="Empresa del agente"
							maxlength={200}
							disabled={loading}
						/>
					</div>
				</div>
			</div>

			<!-- Información de contacto -->
			<div class="space-y-4">
				<h3 class="text-sm font-semibold">Información de Contacto</h3>

				<div class="grid grid-cols-2 gap-4">
					<div class="space-y-2">
						<Label for="edit-phone">Teléfono</Label>
						<Input
							id="edit-phone"
							value={formData.phone}
							oninput={(e) => {
								formData.phone = e.currentTarget.value.replace(/[^\d\s\-\+\(\)]/g, '');
								e.currentTarget.value = formData.phone;
							}}
							placeholder="Número telefónico"
							maxlength={30}
							disabled={loading}
						/>
					</div>

					<div class="space-y-2">
						<Label for="edit-fax">Fax</Label>
						<Input
							id="edit-fax"
							value={formData.fax}
							oninput={(e) => {
								formData.fax = e.currentTarget.value.replace(/[^\d\s\-\+\(\)]/g, '');
								e.currentTarget.value = formData.fax;
							}}
							placeholder="Número de fax"
							maxlength={30}
							disabled={loading}
						/>
					</div>
				</div>

				<div class="space-y-2">
					<Label for="edit-email">Email</Label>
					<Input
						id="edit-email"
						type="email"
						bind:value={formData.email}
						placeholder="correo@ejemplo.com"
						maxlength={100}
						disabled={loading}
					/>
				</div>

				<div class="space-y-2">
					<Label for="edit-contact">Contacto</Label>
					<Input
						id="edit-contact"
						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"
						maxlength={80}
						disabled={loading}
					/>
				</div>
			</div>

			<!-- Dirección -->
			<div class="space-y-4">
				<h3 class="text-sm font-semibold">Dirección</h3>

				<div class="space-y-2">
					<Label for="edit-address">Dirección</Label>
					<Input
						id="edit-address"
						bind:value={formData.address}
						placeholder="Calle y número"
						maxlength={1500}
						disabled={loading}
					/>
				</div>

				<div class="grid grid-cols-3 gap-4">
					<div class="space-y-2">
						<Label for="edit-postal_code">Código Postal</Label>
						<Input
							id="edit-postal_code"
							bind:value={formData.postal_code}
							placeholder="C.P."
							maxlength={15}
							disabled={loading}
							oninput={(e) => {
								formData.postal_code = e.currentTarget.value.replace(/[^a-zA-Z0-9]/g, '');
							}}
						/>
					</div>

					<div class="space-y-2">
						<Label for="edit-city">Ciudad</Label>
						<Input
							id="edit-city"
							bind:value={formData.city}
							placeholder="Ciudad"
							maxlength={30}
							disabled={loading}
						/>
					</div>

					<div class="space-y-2">
						<Label for="edit-state">Estado</Label>
						<Input
							id="edit-state"
							bind:value={formData.state}
							placeholder="Estado"
							maxlength={30}
							disabled={loading}
						/>
					</div>
				</div>

				<div class="space-y-2">
					<Label for="edit-country">País</Label>
					<Input
						id="edit-country"
						bind:value={formData.country}
						placeholder="País"
						maxlength={3}
						disabled={loading}
					/>
				</div>
			</div>

			<!-- Información fiscal -->
			<div class="space-y-4">
				<h3 class="text-sm font-semibold">Información Fiscal</h3>

				<div class="grid grid-cols-2 gap-4">
					<div class="space-y-2">
						<Label for="edit-tax_id">RFC</Label>
						<Input
							id="edit-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"
							maxlength={13}
							disabled={loading}
						/>
					</div>

					<div class="space-y-2">
						<Label for="edit-personal_id">CURP</Label>
						<Input
							id="edit-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"
							maxlength={18}
							disabled={loading}
						/>
					</div>
				</div>

				<div class="space-y-2">
					<Label for="edit-position">Posición</Label>
					<Input
						id="edit-position"
						bind:value={formData.position}
						placeholder="Cargo o posición"
						maxlength={30}
						disabled={loading}
					/>
				</div>
			</div>

			<Dialog.Footer>
				<Button type="button" variant="outline" onclick={() => (open = false)} disabled={loading}>
					Cancelar
				</Button>
				<Button type="submit" disabled={loading}>
					{#if loading}
						<div class="flex items-center gap-2">
							<div
								class="h-4 w-4 animate-spin rounded-full border-2 border-primary-foreground border-t-transparent"
							></div>
							Guardando...
						</div>
					{:else}
						Guardar Cambios
					{/if}
				</Button>
			</Dialog.Footer>
		</form>
	</Dialog.Content>
</Dialog.Root>
