<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 * as Select from '$lib/components/ui/select';
	import { trailersApi, type Trailer } from '$lib/api/dashboard/a76/trailers';
	import { trailerTypesApi, type TrailerType } from '$lib/api/dashboard/reference_data/trailer_types';
	import { countriesApi, type Country } from '$lib/api/dashboard/reference_data/countries';
	import { statesApi, type State } from '$lib/api/dashboard/reference_data/states';
	import { companyStore } from '$lib/stores/company.svelte';
	import { browser } from '$app/environment';
	import { onMount, onDestroy } from 'svelte';

	let {
		open = $bindable(false),
		item = null,
		onSuccess
	}: {
		open: boolean;
		item?: Trailer | null;
		onSuccess?: () => void;
	} = $props();

	const isEdit = $derived(!!item);
	const title = $derived(isEdit ? 'Editar Trailer' : 'Nuevo Trailer');

	let formData = $state<Trailer>({
		trailer_number: '',
		ace_trailer_number: '',
		trailer_type_key: '',
		seal: '',
		entity_code: '',
		plate_number: '',
		state: '',
		country: '',
		container_key: ''
	});

	let loading = $state(false);
	let error = $state<string | null>(null);
	let trailerTypes = $state<TrailerType[]>([]);
	let countries = $state<Country[]>([]);
	let states = $state<State[]>([]);
	let refsLoading = $state(false);

	const ENTITY_OPTS = [
		{ value: '', label: '— Sin código —' },
		{ value: 'C', label: 'C' },
		{ value: 'I', label: 'I' },
		{ value: 'A', label: 'A' },
		{ value: 'B', label: 'B' }
	];

	const countryM3 = $derived(
		countries.find((c) => c.ame_key === formData.country)?.m3_key ?? null
	);

	const statesFiltered = $derived(
		countryM3 ? states.filter((s) => s.m3_key === countryM3) : states
	);

	function emptyTrailerForm(): Trailer {
		return {
			trailer_number: '',
			ace_trailer_number: '',
			trailer_type_key: '',
			seal: '',
			entity_code: '',
			plate_number: '',
			state: '',
			country: '',
			container_key: ''
		};
	}

	async function loadReferenceData() {
		if (!browser) return;
		refsLoading = true;
		try {
			const [tt, cc, ss] = await Promise.all([
				trailerTypesApi.list(1, 100),
				countriesApi.list(1, 100),
				statesApi.list(1, 100)
			]);
			if (tt.data?.items) trailerTypes = tt.data.items;
			if (cc.data?.items) countries = cc.data.items;
			if (ss.data?.items) states = ss.data.items;
		} catch {
			trailerTypes = [];
			countries = [];
			states = [];
		} finally {
			refsLoading = false;
		}
	}

	$effect(() => {
		if (!open) {
			error = null;
			loading = false;
			return;
		}
		if (item) {
			formData = { ...item };
		} else {
			formData = emptyTrailerForm();
		}
		void loadReferenceData();
	});

	async function handleSubmit() {
		if (loading) return;
		error = null;
		loading = true;

		try {
			const companyId = companyStore.activeCompany?.id;
			if (!companyId) {
				throw new Error('No hay una compañía seleccionada');
			}

			if (!formData.trailer_number.trim()) {
				throw new Error('El número de trailer es requerido');
			}

			let response;
			if (isEdit && item) {
				response = await trailersApi.update(item.trailer_number, formData, companyId);
			} else {
				response = await trailersApi.create(formData, companyId);
			}

			if (response.error) {
				const ve = (response as { validationErrors?: { msg?: string; col?: string }[] })
					.validationErrors;
				if (ve?.length) {
					throw new Error(ve.map((e) => e.msg || e.col).join(' · '));
				}
				throw new Error(response.error);
			}

			open = false;
			if (onSuccess) {
				onSuccess();
			}
		} catch (e) {
			error = e instanceof Error ? e.message : 'Error al guardar el trailer';
		} finally {
			loading = false;
		}
	}

	function handleCancel() {
		open = false;
		error = null;
	}

	function onSaveFormEvent() {
		void handleSubmit();
	}

	$effect(() => {
		if (!browser) return;
		document.addEventListener('save-form', onSaveFormEvent);
		return () => document.removeEventListener('save-form', onSaveFormEvent);
	});
</script>

<Dialog.Root bind:open>
	<Dialog.Content class="max-h-[90vh] overflow-y-auto sm:max-w-5xl">
		<Dialog.Header>
			<Dialog.Title>{title}</Dialog.Title>
			<Dialog.Description>
				{isEdit
					? 'Modifica los datos del trailer'
					: 'Completa los datos para crear un nuevo trailer'}
			</Dialog.Description>
		</Dialog.Header>

		<form
			onsubmit={(e) => {
				e.preventDefault();
				handleSubmit();
			}}
			class="space-y-6"
		>
			{#if error}
				<div class="rounded-md bg-destructive/15 p-3 text-sm text-destructive">
					{error}
				</div>
			{/if}

			<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
				<div class="grid gap-2">
					<Label for="trailer_number"
						>Número de Trailer <span class="text-destructive">*</span></Label
					>
					<Input
						id="trailer_number"
						bind:value={formData.trailer_number}
						disabled={isEdit}
						required
						maxlength={20}
					/>
				</div>

				<div class="grid gap-2">
					<Label for="plate_number">Placas</Label>
					<Input id="plate_number" bind:value={formData.plate_number} maxlength={17} />
				</div>

				<div class="grid gap-2">
					<Label for="ace_trailer_number">Número Trailer ACE</Label>
					<Input id="ace_trailer_number" bind:value={formData.ace_trailer_number} maxlength={10} />
				</div>

				<div class="grid gap-2">
					<Label for="trailer_type_key">Tipo de Trailer</Label>
					<Select.Root type="single" bind:value={formData.trailer_type_key} disabled={refsLoading}>
						<Select.Trigger class="w-full" id="trailer_type_key">
							{refsLoading
								? 'Cargando tipos...'
								: formData.trailer_type_key
									? `${formData.trailer_type_key} — ${trailerTypes.find((t) => t.trailer_type_key === formData.trailer_type_key)?.description ?? ''}`
									: '— Sin tipo (opcional) —'}
						</Select.Trigger>
						<Select.Content>
							<Select.Item value="" label="Sin tipo">— Sin tipo —</Select.Item>
							{#each trailerTypes as t}
								<Select.Item value={t.trailer_type_key} label={t.trailer_type_key}>
									{t.trailer_type_key}
									{#if t.description}
										<span class="text-muted-foreground"> — {t.description}</span>
									{/if}
								</Select.Item>
							{/each}
						</Select.Content>
					</Select.Root>
					<p class="text-xs text-muted-foreground">Catálogo SAT. Vacío si no aplica.</p>
				</div>

				<div class="grid gap-2">
					<Label for="container_key">Contenedor (Clave)</Label>
					<Input
						id="container_key"
						bind:value={formData.container_key}
						maxlength={3}
						placeholder="3 car."
					/>
				</div>

				<div class="grid gap-2">
					<Label for="seal">Sello</Label>
					<Input id="seal" bind:value={formData.seal} maxlength={15} />
				</div>

				<div class="grid gap-2">
					<Label for="entity_code">Código Entidad</Label>
					<Select.Root type="single" bind:value={formData.entity_code}>
						<Select.Trigger class="w-full" id="entity_code">
							{ENTITY_OPTS.find((o) => o.value === (formData.entity_code || ''))?.label ??
								'— Sin código —'}
						</Select.Trigger>
						<Select.Content>
							{#each ENTITY_OPTS as o}
								<Select.Item value={o.value} label={o.label}>{o.label}</Select.Item>
							{/each}
						</Select.Content>
					</Select.Root>
				</div>

				<div class="grid grid-cols-2 gap-4 md:col-span-2">
					<div class="grid gap-2">
						<Label for="country">País (clave americana)</Label>
						<Select.Root type="single" bind:value={formData.country} disabled={refsLoading}>
							<Select.Trigger class="w-full" id="country">
								{refsLoading
									? '...'
									: formData.country
										? `${formData.country} — ${countries.find((c) => c.ame_key === formData.country)?.description_es ?? ''}`
										: '— Opcional —'}
							</Select.Trigger>
							<Select.Content class="max-h-60">
								<Select.Item value="" label="Vacío">— Vacío —</Select.Item>
								{#each countries as c}
									<Select.Item value={c.ame_key} label={c.ame_key}>
										{c.ame_key} — {c.description_es}
									</Select.Item>
								{/each}
							</Select.Content>
						</Select.Root>
					</div>
					<div class="grid gap-2">
						<Label for="state">Estado / provincia</Label>
						<Select.Root type="single" bind:value={formData.state} disabled={refsLoading}>
							<Select.Trigger class="w-full" id="state">
								{refsLoading
									? '...'
									: formData.state ||
										(formData.country ? '— Selecciona —' : '— Primero el país —')}
							</Select.Trigger>
							<Select.Content class="max-h-60">
								<Select.Item value="" label="Vacío">— Vacío —</Select.Item>
								{#each statesFiltered as s}
									<Select.Item value={s.description} label={s.description}>
										{s.description}
									</Select.Item>
								{/each}
							</Select.Content>
						</Select.Root>
					</div>
				</div>
			</div>

			<Dialog.Footer>
				<Button type="button" variant="outline" onclick={handleCancel} disabled={loading}>
					Cancelar
				</Button>
				<Button type="submit" disabled={loading}>
					{loading ? 'Guardando...' : isEdit ? 'Actualizar' : 'Crear'}
				</Button>
			</Dialog.Footer>
		</form>
	</Dialog.Content>
</Dialog.Root>
