<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 UnitMeasureSelectorDialog from '$lib/components/dashboard/goods/modales/unit-measure-dialog.svelte';
	import { FolderSearch, Scale } from 'lucide-svelte';
	import {
		createUnitConversion,
		updateUnitConversion,
		type UnitConversion
	} from '$lib/api/dashboard/a76/general_catalogs/unit-conversions';
	import { companyStore } from '$lib/stores/company.svelte';
	import { obtenerAtajosFormularioConversiones } from '$lib/config/shortcuts/dashboard/general_catalogs/unit_conversions/edit';

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

	// Atajos

	const currentConversion = $derived(item ?? conversion);
	const isEdit = $derived(mode === 'edit' || !!currentConversion);
	const title = $derived(isEdit ? 'Editar Conversión' : 'Nueva Conversión');

	let formData = $state({
		from_unit_code: '',
		to_unit_code: '',
		conversion_factor: ''
	});

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

	$effect(() => {
		if (!open) return;

		if (currentConversion) {
			formData = {
				from_unit_code: currentConversion.from_unit_code || '',
				to_unit_code: currentConversion.to_unit_code || '',
				conversion_factor: currentConversion.conversion_factor.toString() || ''
			};
		} else {
			formData = {
				from_unit_code: '',
				to_unit_code: '',
				conversion_factor: ''
			};
		}

		error = null;
		loading = false;
		showFromUomModal = false;
		showToUomModal = false;
	});

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

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

			if (!formData.from_unit_code.trim()) throw new Error('El código origen es requerido');
			if (!formData.to_unit_code.trim()) throw new Error('El código destino es requerido');
			if (!formData.conversion_factor || formData.conversion_factor === '')
				throw new Error('El factor de conversión es requerido');

			const dataToSend = {
				from_unit_code: formData.from_unit_code.trim(),
				to_unit_code: formData.to_unit_code.trim(),
				conversion_factor: parseFloat(formData.conversion_factor)
			};

			if (isNaN(dataToSend.conversion_factor)) {
				throw new Error('El factor de conversión debe ser un número válido');
			}

			if (isEdit && currentConversion) {
				await updateUnitConversion(currentConversion.id, dataToSend, companyId);
			} else {
				await createUnitConversion(dataToSend, companyId);
			}

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

<Dialog.Root bind:open>
	<Dialog.Content class="max-w-md">
		<Dialog.Header>
			<Dialog.Title>{title}</Dialog.Title>
		</Dialog.Header>

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

			<div class="grid gap-4 py-4">
				<div class="grid gap-2">
					<Label for="from_unit_code">Código origen <span class="text-destructive">*</span></Label>
					<div class="flex gap-2">
						<div class="relative w-full">
							<Scale class="absolute top-2.5 left-3 h-4 w-4 text-muted-foreground" />
							<Input
								id="from_unit_code"
								bind:value={formData.from_unit_code}
								readonly
								onclick={() => (showFromUomModal = true)}
								class="cursor-pointer pl-9 font-mono"
								placeholder="Seleccione..."
								disabled={loading}
								required
							/>
						</div>
						<Button
							variant="outline"
							size="icon"
							type="button"
							onclick={() => (showFromUomModal = true)}
							disabled={loading}
							class="shrink-0"
						>
							<FolderSearch class="h-4 w-4" />
						</Button>
					</div>
				</div>

				<div class="grid gap-2">
					<Label for="to_unit_code">Código destino <span class="text-destructive">*</span></Label>
					<div class="flex gap-2">
						<div class="relative w-full">
							<Scale class="absolute top-2.5 left-3 h-4 w-4 text-muted-foreground" />
							<Input
								id="to_unit_code"
								bind:value={formData.to_unit_code}
								readonly
								onclick={() => (showToUomModal = true)}
								class="cursor-pointer pl-9 font-mono"
								placeholder="Seleccione..."
								disabled={loading}
								required
							/>
						</div>
						<Button
							variant="outline"
							size="icon"
							type="button"
							onclick={() => (showToUomModal = true)}
							disabled={loading}
							class="shrink-0"
						>
							<FolderSearch class="h-4 w-4" />
						</Button>
					</div>
				</div>

				<div class="grid gap-2">
					<Label for="conversion_factor"
						>Factor de conversión <span class="text-destructive">*</span></Label
					>
					<Input
						id="conversion_factor"
						type="number"
						step="0.000001"
						bind:value={formData.conversion_factor}
						disabled={loading}
						required
					/>
				</div>
			</div>

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

<UnitMeasureSelectorDialog
	bind:open={showFromUomModal}
	onSelect={(u) => {
		formData.from_unit_code = u.code;
	}}
/>

<UnitMeasureSelectorDialog
	bind:open={showToUomModal}
	onSelect={(u) => {
		formData.to_unit_code = u.code;
	}}
/>
