<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 { trailersApi, type Trailer } from '$lib/api/dashboard/a76/trailers';
	import { companyStore } from '$lib/stores/company.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);

	$effect(() => {
		if (item) {
			formData = { ...item };
		} else {
			formData = {
				trailer_number: '',
				ace_trailer_number: '',
				trailer_type_key: '',
				seal: '',
				entity_code: '',
				plate_number: '',
				state: '',
				country: '',
				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');
			}

			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) {
				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;
	}
</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 (Clave)</Label>
					<Input
						id="trailer_type_key"
						bind:value={formData.trailer_type_key}
						maxlength={2}
						placeholder="2 car."
					/>
				</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>
					<Input
						id="entity_code"
						bind:value={formData.entity_code}
						maxlength={1}
						placeholder="1 car."
					/>
				</div>

				<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} placeholder="Ej: TX" />
					</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>

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