<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 { FolderSearch, Scale } from 'lucide-svelte';
	import UnitMeasureSelectorDialog from '$lib/components/dashboard/goods/modales/unit-measure-dialog.svelte';
	import { companyStore } from '$lib/stores/company.svelte';
	import {
		createEquivalencyItem,
		updateEquivalencyItem,
		type EquivalencyItem
	} from '$lib/api/dashboard/a76/general_catalogs/equivalencies';
	import type { UnitOfMeasure } from '$lib/api/dashboard/a76/general_catalogs/units-of-measure';

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

	const isEdit = $derived(!!item);
	const title = $derived(
		isEdit
			? `Editar: ${item?.original_field || ''} → ${item?.external_field || ''}`
			: 'Insertar detalle de equivalencia'
	);

	let formData = $state({
		original_field: '',
		external_field: ''
	});

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

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

		if (item) {
			formData.original_field = item.original_field || '';
			formData.external_field = item.external_field || '';
		} else {
			formData.original_field = defaultOriginalField ?? '';
			formData.external_field = '';
		}

		error = null;
	});

	function handleSelectOriginal(unit: UnitOfMeasure) {
		formData.original_field = unit.code;
		showOriginalModal = false;
	}

	function handleSelectExternal(unit: UnitOfMeasure) {
		formData.external_field = unit.code;
		showExternalModal = false;
	}

	async function handleSubmit() {
		const companyId = companyStore.activeCompany?.id;
		if (!companyId) {
			error = 'No hay compañía seleccionada';
			return;
		}

		loading = true;
		error = null;

		try {
			if (!formData.original_field.trim()) throw new Error('Campo original requerido');
			if (!formData.external_field.trim()) throw new Error('Campo externo requerido');

			const dataToSend = {
				original_field: formData.original_field.trim(),
				external_field: formData.external_field.trim()
			};

			if (isEdit && item) {
				await updateEquivalencyItem(item.id, dataToSend, companyId);
			} else {
				await createEquivalencyItem(dataToSend, companyId);
			}

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

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

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

			<div class="grid gap-4 py-4">
				<div class="grid gap-2">
					<Label for="original_field">
						Campo Original <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="original_field"
								bind:value={formData.original_field}
								readonly
								onclick={() => (showOriginalModal = true)}
								class="cursor-pointer pl-9 font-mono"
								placeholder="Seleccione..."
								disabled={loading}
								required
							/>
						</div>
						<Button
							variant="outline"
							size="icon"
							type="button"
							onclick={() => (showOriginalModal = true)}
							disabled={loading}
							class="shrink-0"
						>
							<FolderSearch class="h-4 w-4" />
						</Button>
					</div>
				</div>

				<div class="grid gap-2">
					<Label for="external_field">
						Campo Exterior <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="external_field"
								bind:value={formData.external_field}
								readonly
								onclick={() => (showExternalModal = true)}
								class="cursor-pointer pl-9 font-mono"
								placeholder="Seleccione..."
								disabled={loading}
								required
							/>
						</div>
						<Button
							variant="outline"
							size="icon"
							type="button"
							onclick={() => (showExternalModal = true)}
							disabled={loading}
							class="shrink-0"
						>
							<FolderSearch class="h-4 w-4" />
						</Button>
					</div>
				</div>
			</div>

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

<UnitMeasureSelectorDialog bind:open={showOriginalModal} onSelect={handleSelectOriginal} />
<UnitMeasureSelectorDialog bind:open={showExternalModal} onSelect={handleSelectExternal} />
