<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 { companyStore } from '$lib/stores/company.svelte';
	import { Scale } from 'lucide-svelte';
	import {
		createEquivalencyItem,
		updateEquivalencyItem,
		type EquivalencyItem
	} from '$lib/api/dashboard/a76/general_catalogs/equivalencies';

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

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

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

		error = null;
	});

	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="from_unit_code">
						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="from_unit_code"
							bind:value={formData.original_field}
							class="pl-9 font-mono"
							placeholder="Ej: PZA, KGM..."
							disabled={loading}
							required
						/>
						</div>
					</div>
				</div>

				<div class="grid gap-2">
					<Label for="to_unit_code">
						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="to_unit_code"
							bind:value={formData.external_field}
							class="pl-9 font-mono"
							placeholder="Ej: PIEZAS, KGS..."
							disabled={loading}
							required
						/>
						</div>
					</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>
