<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 {
		createPort,
		updatePort,
		type Port,
		PortType
	} from '$lib/api/dashboard/a76/general_catalogs/ports';
	import { companyStore } from '$lib/stores/company.svelte';
	import { obtenerAtajosFormularioPuertos } from '$lib/config/shortcuts/dashboard/general_catalogs/ports/edit';

	let {
		open = $bindable(false),
		mode = 'create',
		item = null,
		onSuccess
	}: {
		open: boolean;
		mode?: 'create' | 'edit';
		item?: Port | null;
		onSuccess?: () => void;
	} = $props();

	const isEdit = $derived(mode === 'edit' || !!item);
	const title = $derived(isEdit ? 'Editar Puerto' : 'Nuevo Puerto');

	/** Alineado con `PortCreate` / columnas en backend (ports/dto.py, models.py) */
	const MAX_PORT_CODE = 6;
	const MAX_LOCATION_CODE = 4;
	const MAX_DESCRIPTION = 20;

	// Atajos

	let formData = $state({
		port_code: '',
		description: '',
		location_code: '',
		location_description: '',
		port_type: PortType.ENTRY
	});

	let loading = $state(false);
	let error = $state<string | null>(null);

	$effect(() => {
		if (open) {
			if (isEdit && item) {
				formData = {
					port_code: item.port_code,
					description: item.description || '',
					location_code: item.location_code,
					location_description: item.location_description || '',
					port_type: item.port_type
				};
			} else {
				formData = {
					port_code: '',
					description: '',
					location_code: '',
					location_description: '',
					port_type: PortType.ENTRY
				};
			}
			error = null;
		}
	});

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

		try {
			const companyId = companyStore.activeCompany?.id;
			if (!companyId) {
				error = 'Selecciona una compañía para guardar el puerto';
				return;
			}

			let response;
			if (isEdit && item) {
				response = await updatePort(
					item.id,
					{
						port_code: formData.port_code,
						description: formData.description || null,
						location_code: formData.location_code,
						location_description: formData.location_description || null,
						port_type: formData.port_type
					},
					companyId
				);
			} else {
				response = await createPort(
					{
						port_code: formData.port_code,
						description: formData.description || null,
						location_code: formData.location_code,
						location_description: formData.location_description || null,
						port_type: formData.port_type
					},
					companyId
				);
			}

			if (response.error) {
				error = response.error;
				return;
			}

			open = false;
			if (onSuccess) onSuccess();
		} catch (e) {
			error = 'Error de conexión';
			console.error(e);
		} finally {
			loading = false;
		}
	}

	function handleCancel() {
		if (loading) return;
		open = false;
	}
</script>

<Dialog.Root bind:open>
	<Dialog.Content class="sm:max-w-[425px]">
		<Dialog.Header>
			<Dialog.Title>{title}</Dialog.Title>
		</Dialog.Header>

		<div class="grid gap-4 py-4">
			{#if error}
				<div class="text-red-500 text-sm mb-2">{error}</div>
			{/if}

			<div class="grid grid-cols-4 items-center gap-4">
				<Label for="port_code" class="text-right">Código Puerto</Label>
				<Input
					id="port_code"
					bind:value={formData.port_code}
					class="col-span-3"
					maxlength={MAX_PORT_CODE}
					placeholder={`Máx. ${MAX_PORT_CODE} caracteres`}
					autocomplete="off"
					spellcheck={false}
					disabled={loading}
				/>
			</div>

			<div class="grid grid-cols-4 items-center gap-4">
				<Label for="description" class="text-right">Descripción Puerto</Label>
				<Input
					id="description"
					bind:value={formData.description}
					class="col-span-3"
					maxlength={MAX_DESCRIPTION}
					placeholder={`Máx. ${MAX_DESCRIPTION} caracteres`}
					autocomplete="off"
					spellcheck={false}
					disabled={loading}
				/>
			</div>

			<div class="grid grid-cols-4 items-center gap-4">
				<Label for="location_code" class="text-right">Código Ubicación</Label>
				<Input
					id="location_code"
					bind:value={formData.location_code}
					class="col-span-3"
					maxlength={MAX_LOCATION_CODE}
					placeholder={`Máx. ${MAX_LOCATION_CODE} caracteres`}
					autocomplete="off"
					spellcheck={false}
					disabled={loading}
				/>
			</div>

			<div class="grid grid-cols-4 items-center gap-4">
				<Label for="location_description" class="text-right">Descripción Ubicación</Label>
				<Input
					id="location_description"
					bind:value={formData.location_description}
					class="col-span-3"
					maxlength={MAX_DESCRIPTION}
					placeholder={`Máx. ${MAX_DESCRIPTION} caracteres`}
					autocomplete="off"
					spellcheck={false}
					disabled={loading}
				/>
			</div>

			<div class="grid grid-cols-4 items-center gap-4">
				<Label for="port_type" class="text-right">Tipo</Label>
				<div class="col-span-3">
					<Select.Root type="single" bind:value={formData.port_type}>
						<Select.Trigger>
							{formData.port_type === 'ENTRY'
								? 'Entrada'
								: formData.port_type === 'EXIT'
									? 'Salida'
									: formData.port_type === 'BOTH'
										? 'Ambos'
										: 'Seleccionar'}
						</Select.Trigger>
						<Select.Content>
							<Select.Item value="ENTRY">Entrada</Select.Item>
							<Select.Item value="EXIT">Salida</Select.Item>
							<Select.Item value="BOTH">Ambos</Select.Item>
						</Select.Content>
					</Select.Root>
				</div>
			</div>
		</div>

		<Dialog.Footer>
			<Button type="button" variant="outline" onclick={handleCancel} disabled={loading}>
				Cancelar
			</Button>
			<Button type="button" onclick={handleSubmit} disabled={loading}>
				{loading ? 'Guardando...' : 'Guardar'}
			</Button>
		</Dialog.Footer>
	</Dialog.Content>
</Dialog.Root>
