<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 * as Tabs from '$lib/components/ui/tabs';
	import { vehiclesApi, type Vehicle } from '$lib/api/dashboard/a76/vehicles';
	import { transportersApi, type Transporter } from '$lib/api/dashboard/a76/transporters';
	import { transportTypesApi } from '$lib/api/dashboard/reference_data/transport_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 { tv, tvTransportType } from '$lib/i18n/vehicles';
	import { browser } from '$app/environment';

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

	// Determinar si es modo edición o creación
	const isEdit = $derived(!!item);
	const title = $derived(isEdit ? tv('dialog_edit_title') : tv('dialog_new_title'));

	// Estado del formulario
	let formData = $state<Vehicle>({
		vehicle_key: '',
		ace_vehicle_key: '',
		transporter_key: '',
		transport_identifier: '',
		transport_type: '',
		entity_code: '',
		transponder_number: '',
		dot_number: '',
		plate_number: '',
		city: '',
		state: '',
		country: '',
		seal: '',
		insurance_company_name: '',
		insurance_number: '',
		insurance_amount: undefined,
		insurance_date: undefined,
		box_number: '',
		brand: '',
		year: '',
		series: '',
		description: '',
		engine_number: '',
		sct_permission: '',
		color: '',
		container_key: ''
	});

	let loading = $state(false);
	let error = $state<string | null>(null);
	let transporters = $state<Transporter[]>([]);
	let transportTypes = $state<{ transport_code: string; description: string }[]>([]);
	let countries = $state<Country[]>([]);
	let states = $state<State[]>([]);
	let refsLoading = $state(false);

	const ENTITY_OPTS = [
		{ value: '', label: tv('no_code') },
		{ value: 'C', label: 'C' },
		{ value: 'I', label: 'I' },
		{ value: 'A', label: 'A' },
		{ value: 'B', label: 'B' }
	];

	function getTransportTypeText(transportCode?: string, description?: string): string {
		return tvTransportType(transportCode, description);
	}

	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
	);

	async function loadReferenceData() {
		if (!browser || !companyStore.activeCompany?.id) return;
		refsLoading = true;
		const cid = companyStore.activeCompany.id;
		try {
			const [tr, tt, cc, ss] = await Promise.all([
				transportersApi.list(cid, { page: 1, page_size: 100 }),
				transportTypesApi.list(cid, 1, 100),
				countriesApi.list(1, 100),
				statesApi.list(1, 100)
			]);
			if (tr.data?.items) transporters = tr.data.items;
			if (tt.data?.items) transportTypes = tt.data.items;
			if (cc.data?.items) countries = cc.data.items;
			if (ss.data?.items) states = ss.data.items;
		} catch {
			transporters = [];
			transportTypes = [];
			countries = [];
			states = [];
		} finally {
			refsLoading = false;
		}
	}

	function emptyVehicleForm(): Vehicle {
		return {
			vehicle_key: '',
			ace_vehicle_key: '',
			transporter_key: '',
			transport_identifier: '',
			transport_type: '',
			entity_code: '',
			transponder_number: '',
			dot_number: '',
			plate_number: '',
			city: '',
			state: '',
			country: '',
			seal: '',
			insurance_company_name: '',
			insurance_number: '',
			insurance_amount: undefined,
			insurance_date: undefined,
			box_number: '',
			brand: '',
			year: '',
			series: '',
			description: '',
			engine_number: '',
			sct_permission: '',
			color: '',
			container_key: ''
		};
	}

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

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

		try {
			const companyId = companyStore.activeCompany?.id;
			if (!companyId) {
				throw new Error(tv('no_company_selected'));
			}

			// Validación básica
			if (!formData.vehicle_key.trim()) {
				throw new Error(tv('vehicle_key_required'));
			}

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

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

			// Cerrar diálogo y notificar éxito
			open = false;
			if (onSuccess) {
				onSuccess();
			}
		} catch (e) {
			error = e instanceof Error ? e.message : tv('save_error');
		} 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-[95vh] max-w-3xl overflow-y-auto">
		<Dialog.Header>
			<Dialog.Title>{title}</Dialog.Title>
			<Dialog.Description>
				{isEdit
					? tv('dialog_edit_description')
					: tv('dialog_new_description')}
			</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}

			<Tabs.Root value="general" class="w-full">
				<Tabs.List class="grid w-full grid-cols-2">
					<Tabs.Trigger value="general">{tv('tab_general')}</Tabs.Trigger>
					<Tabs.Trigger value="details">{tv('tab_details')}</Tabs.Trigger>
				</Tabs.List>

				<Tabs.Content value="general" class="mt-6 space-y-8">
					<!-- Información del Vehículo -->
					<section class="space-y-4">
						<h3 class="border-b pb-2 text-sm font-bold uppercase tracking-wider text-muted-foreground">
							{tv('section_vehicle_identification')}
						</h3>

						<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
							<div class="grid gap-2 md:col-span-2">
								<Label for="vehicle_key"
									>{tv('label_vehicle_key')} <span class="text-destructive">*</span></Label
								>
								<Input
									id="vehicle_key"
									bind:value={formData.vehicle_key}
									disabled={isEdit}
									required
									maxlength={14}
									placeholder={tv('placeholder_vehicle_key')}
								/>
							</div>

							<div class="grid gap-2">
								<Label for="brand">{tv('label_brand')}</Label>
								<Input id="brand" bind:value={formData.brand} maxlength={20} placeholder={tv('placeholder_brand')} />
							</div>
							<div class="grid gap-2">
								<Label for="year">{tv('label_year')}</Label>
								<Input id="year" bind:value={formData.year} maxlength={4} placeholder={tv('placeholder_year')} />
							</div>

							<div class="grid gap-2">
								<Label for="plate_number">{tv('label_plate_number')}</Label>
								<Input id="plate_number" bind:value={formData.plate_number} maxlength={17} placeholder={tv('placeholder_plate_number')} />
							</div>

							<div class="grid gap-2">
								<Label for="series">{tv('label_series')}</Label>
								<Input id="series" bind:value={formData.series} maxlength={30} placeholder={tv('placeholder_series')} />
							</div>
						</div>
					</section>

					<!-- Datos de Transporte -->
					<section class="space-y-4">
						<h3 class="border-b pb-2 text-sm font-bold uppercase tracking-wider text-muted-foreground">
							{tv('section_transport_data')}
						</h3>

						<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
							<div class="grid gap-2 md:col-span-2">
								<Label for="transporter_key">{tv('label_transporter')}</Label>
								<Select.Root type="single" bind:value={formData.transporter_key} disabled={refsLoading}>
									<Select.Trigger class="w-full">
										{refsLoading
											? '...'
											: formData.transporter_key
												? `${formData.transporter_key} — ${transporters.find((t) => t.transporter_key === formData.transporter_key)?.name ?? ''}`
												: tv('select_transporter')}
									</Select.Trigger>
									<Select.Content class="max-h-60">
										<Select.Item value="" label={tv('empty')}>{tv('empty')}</Select.Item>
										{#each transporters as t}
											<Select.Item value={t.transporter_key} label={t.transporter_key}>
												{t.transporter_key} — {t.name || t.short_name || ''}
											</Select.Item>
										{/each}
									</Select.Content>
								</Select.Root>
							</div>

							<div class="grid gap-2">
								<Label for="transport_identifier">{tv('label_transport_identifier')}</Label>
								<Input
									id="transport_identifier"
									bind:value={formData.transport_identifier}
									maxlength={30}
									placeholder={tv('placeholder_transport_identifier')}
								/>
							</div>

							<div class="grid gap-2">
								<Label for="transport_type">{tv('label_transport_type')}</Label>
								<Select.Root type="single" bind:value={formData.transport_type} disabled={refsLoading}>
									<Select.Trigger class="w-full" id="transport_type">
										{refsLoading
											? '...'
											: formData.transport_type
												? `${formData.transport_type} — ${getTransportTypeText(formData.transport_type, transportTypes.find((x) => (x.transport_code || '').trim().toUpperCase() === (formData.transport_type || '').trim().toUpperCase())?.description)}`
												: tv('optional')}
									</Select.Trigger>
									<Select.Content>
										<Select.Item value="" label={tv('empty')}>{tv('empty')}</Select.Item>
										{#each transportTypes as x}
											<Select.Item value={x.transport_code} label={x.transport_code}>
												{x.transport_code} — {getTransportTypeText(x.transport_code, x.description)}
											</Select.Item>
										{/each}
									</Select.Content>
								</Select.Root>
							</div>

							<div class="grid gap-2">
								<Label for="entity_code">{tv('label_entity_code')}</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 ??
											tv('no_code')}
									</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>
								<p class="text-[10px] text-muted-foreground uppercase">{tv('entity_required_hint')}</p>
							</div>

							<div class="grid gap-2">
								<Label for="sct_permission">{tv('label_sct_permission')}</Label>
								<Input id="sct_permission" bind:value={formData.sct_permission} maxlength={40} placeholder={tv('placeholder_sct_permission')} />
							</div>
						</div>
					</section>
				</Tabs.Content>

				<Tabs.Content value="details" class="mt-6 space-y-8">
					<!-- Seguro y Otros -->
					<section class="space-y-4">
						<h3 class="border-b pb-2 text-sm font-bold uppercase tracking-wider text-muted-foreground">
							{tv('section_insurance')}
						</h3>

						<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
							<div class="grid gap-2 md:col-span-2">
								<Label for="insurance_company_name">{tv('label_insurance_company')}</Label>
								<Input
									id="insurance_company_name"
									bind:value={formData.insurance_company_name}
									maxlength={30}
									placeholder={tv('placeholder_insurance_company')}
								/>
							</div>

							<div class="grid gap-2">
								<Label for="insurance_number">{tv('label_insurance_number')}</Label>
								<Input
									id="insurance_number"
									bind:value={formData.insurance_number}
									maxlength={20}
									placeholder={tv('placeholder_insurance_number')}
								/>
							</div>
							<div class="grid gap-2">
								<Label for="insurance_amount">{tv('label_insurance_amount')}</Label>
								<Input
									id="insurance_amount"
									type="number"
									bind:value={formData.insurance_amount}
									placeholder="0.00"
								/>
							</div>

							<div class="grid gap-2">
								<Label for="dot_number">{tv('label_dot_number')}</Label>
								<Input id="dot_number" bind:value={formData.dot_number} maxlength={8} placeholder="DOT ID" />
							</div>
						</div>
					</section>

					<!-- Ubicación y Detalles -->
					<section class="space-y-4">
						<h3 class="border-b pb-2 text-sm font-bold uppercase tracking-wider text-muted-foreground">
							{tv('section_location')}
						</h3>

						<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
							<div class="grid gap-2">
								<Label for="country">{tv('label_country')}</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 ?? ''}`
												: tv('optional')}
									</Select.Trigger>
									<Select.Content class="max-h-60">
										<Select.Item value="" label={tv('empty')}>{tv('empty')}</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">{tv('label_state')}</Label>
								<Select.Root type="single" bind:value={formData.state} disabled={refsLoading}>
									<Select.Trigger class="w-full" id="state">
										{refsLoading
											? '...'
											: formData.state ||
												(formData.country ? tv('select_state') : tv('select_country_first'))}
									</Select.Trigger>
									<Select.Content class="max-h-60">
										<Select.Item value="" label={tv('empty')}>{tv('empty')}</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 class="grid gap-2">
								<Label for="city">{tv('label_city')}</Label>
								<Input id="city" bind:value={formData.city} maxlength={30} placeholder={tv('placeholder_city')} />
							</div>
							<div class="grid gap-2">
								<Label for="color">{tv('label_color')}</Label>
								<Input id="color" bind:value={formData.color} maxlength={20} placeholder={tv('placeholder_color')} />
							</div>

							<div class="grid gap-2">
								<Label for="container_key">{tv('label_container_type')}</Label>
								<Input
									id="container_key"
									bind:value={formData.container_key}
									maxlength={3}
									placeholder={tv('placeholder_container_type')}
								/>
							</div>
						</div>
					</section>

					<section class="space-y-4 pt-4">
						<div class="grid gap-2">
							<Label for="description">{tv('label_additional_description')}</Label>
							<Input
								id="description"
								bind:value={formData.description}
								maxlength={100}
								placeholder={tv('placeholder_additional_description')}
							/>
						</div>
					</section>
				</Tabs.Content>
			</Tabs.Root>

			<Dialog.Footer>
				<Button type="button" variant="outline" onclick={handleCancel} disabled={loading}>
					{tv('cancel')}
				</Button>
				<Button type="submit" disabled={loading}>
					{loading ? tv('saving') : isEdit ? tv('update') : tv('create')}
				</Button>
			</Dialog.Footer>
		</form>
	</Dialog.Content>
</Dialog.Root>
