<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 { vehiclesApi, type Vehicle } from '$lib/api/dashboard/a76/vehicles';
	import { companyStore } from '$lib/stores/company.svelte';

	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 ? 'Editar Vehículo' : 'Nuevo Vehículo');

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

	// Resetear formulario cuando cambia el item
	$effect(() => {
		if (item) {
			formData = { ...item };
		} else {
			formData = {
				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: ''
			};
		}
	});

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

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

			// Validación básica
			if (!formData.vehicle_key.trim()) {
				throw new Error('La clave del vehículo es requerida');
			}

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

			if (response.error) {
				throw new Error(response.error);
			}

			// Cerrar diálogo y notificar éxito
			open = false;
			if (onSuccess) {
				onSuccess();
			}
		} catch (e) {
			error = e instanceof Error ? e.message : 'Error al guardar el vehículo';
		} finally {
			loading = false;
		}
	}

	function handleCancel() {
		open = false;
		error = null;
	}
</script>

<Dialog.Root bind:open>
	<Dialog.Content class="max-h-[90vh] max-w-4xl overflow-y-auto">
		<Dialog.Header>
			<Dialog.Title>{title}</Dialog.Title>
			<Dialog.Description>
				{isEdit
					? 'Modifica los datos del vehículo'
					: 'Completa los datos para crear un nuevo vehículo de transporte'}
			</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-6 md:grid-cols-2">
				<!-- Información del Vehículo -->
				<section class="space-y-4">
					<h3 class="border-b pb-2 text-sm font-semibold">Identificación del Vehículo</h3>

					<div class="grid gap-2">
						<Label for="vehicle_key"
							>Clave del Vehículo <span class="text-destructive">*</span></Label
						>
						<Input
							id="vehicle_key"
							bind:value={formData.vehicle_key}
							disabled={isEdit}
							required
							maxlength={14}
						/>
					</div>

					<div class="grid grid-cols-2 gap-4">
						<div class="grid gap-2">
							<Label for="brand">Marca</Label>
							<Input id="brand" bind:value={formData.brand} maxlength={20} />
						</div>
						<div class="grid gap-2">
							<Label for="year">Año</Label>
							<Input id="year" bind:value={formData.year} maxlength={4} placeholder="YYYY" />
						</div>
					</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="series">Serie / VIN</Label>
						<Input id="series" bind:value={formData.series} maxlength={30} />
					</div>
				</section>

				<!-- Datos de Transporte -->
				<section class="space-y-4">
					<h3 class="border-b pb-2 text-sm font-semibold">Datos de Transporte</h3>

					<div class="grid gap-2">
						<Label for="transporter_key">Clave Transportista</Label>
						<Input id="transporter_key" bind:value={formData.transporter_key} maxlength={23} />
					</div>

					<div class="grid gap-2">
						<Label for="transport_identifier">Identificador Transporte</Label>
						<Input
							id="transport_identifier"
							bind:value={formData.transport_identifier}
							maxlength={30}
						/>
					</div>

					<div class="grid gap-2">
						<Label for="transport_type">Tipo de Transporte</Label>
						<Input
							id="transport_type"
							bind:value={formData.transport_type}
							maxlength={2}
							placeholder="2 car."
						/>
					</div>

					<div class="grid gap-2">
						<Label for="sct_permission">Permiso SCT</Label>
						<Input id="sct_permission" bind:value={formData.sct_permission} maxlength={40} />
					</div>
				</section>

				<!-- Seguro y Otros -->
				<section class="space-y-4">
					<h3 class="border-b pb-2 text-sm font-semibold">Seguro y Otros</h3>

					<div class="grid gap-2">
						<Label for="insurance_company_name">Aseguradora</Label>
						<Input
							id="insurance_company_name"
							bind:value={formData.insurance_company_name}
							maxlength={30}
						/>
					</div>

					<div class="grid grid-cols-2 gap-4">
						<div class="grid gap-2">
							<Label for="insurance_number">Póliza</Label>
							<Input id="insurance_number" bind:value={formData.insurance_number} maxlength={20} />
						</div>
						<div class="grid gap-2">
							<Label for="insurance_amount">Monto Seguro</Label>
							<Input id="insurance_amount" type="number" bind:value={formData.insurance_amount} />
						</div>
					</div>

					<div class="grid gap-2">
						<Label for="dot_number">Número DOT</Label>
						<Input id="dot_number" bind:value={formData.dot_number} maxlength={8} />
					</div>
				</section>

				<!-- Ubicación y Detalles -->
				<section class="space-y-4">
					<h3 class="border-b pb-2 text-sm font-semibold">Ubicación y Detalles</h3>

					<div class="grid grid-cols-2 gap-4">
						<div class="grid gap-2">
							<Label for="state">Estado</Label>
							<Input id="state" bind:value={formData.state} maxlength={30} />
						</div>
						<div class="grid gap-2">
							<Label for="country">País</Label>
							<Input
								id="country"
								bind:value={formData.country}
								maxlength={3}
								placeholder="MEX / USA"
							/>
						</div>
					</div>

					<div class="grid gap-2">
						<Label for="description">Descripción</Label>
						<Input id="description" bind:value={formData.description} maxlength={100} />
					</div>

					<div class="grid grid-cols-2 gap-4">
						<div class="grid gap-2">
							<Label for="color">Color</Label>
							<Input id="color" bind:value={formData.color} maxlength={20} />
						</div>
						<div class="grid gap-2">
							<Label for="container_key">Contenedor</Label>
							<Input
								id="container_key"
								bind:value={formData.container_key}
								maxlength={3}
								placeholder="3 car."
							/>
						</div>
					</div>
				</section>
			</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>
