<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 { 
        createUnitConversion, 
        updateUnitConversion, 
        type UnitConversion 
    } from "$lib/api/dashboard/a76/general_catalogs/unit-conversions"; // 👈 Asegúrate que la ruta del archivo ts coincida
    import { companyStore } from "$lib/stores/company.svelte";

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

    const isEdit = $derived(!!item);
    const title = $derived(isEdit ? "Editar Conversión" : "Nueva Conversión");

    // Estado del formulario
    let formData = $state({
        from_unit_code: '',
        to_unit_code: '',
        conversion_factor: null as number | null
    });

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

    // Cargar datos al abrir
    $effect(() => {
        if (open) {
            if (item) {
                formData = {
                    from_unit_code: item.from_unit_code,
                    to_unit_code: item.to_unit_code,
                    conversion_factor: item.conversion_factor
                };
            } else {
                formData = {
                    from_unit_code: '',
                    to_unit_code: '',
                    conversion_factor: null
                };
            }
            error = null;
        }
    });

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

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

            // Validaciones
            if (!formData.from_unit_code.trim()) throw new Error('La unidad origen es requerida');
            if (!formData.to_unit_code.trim()) throw new Error('La unidad destino es requerida');
            if (formData.conversion_factor === null || formData.conversion_factor === undefined) throw new Error('El factor de conversión es requerido');

            // Preparar datos
            const dataToSend = {
                from_unit_code: formData.from_unit_code.trim().toUpperCase(), // Normalizamos a mayúsculas
                to_unit_code: formData.to_unit_code.trim().toUpperCase(),
                conversion_factor: Number(formData.conversion_factor)
            };

            let response;
            
            // 👇 companyId por fuera (Argumento separado)
            if (isEdit && item) {
                response = await updateUnitConversion(item.id, dataToSend, companyId);
            } else {
                response = await createUnitConversion(dataToSend, companyId);
            }

            open = false;
            if (onSuccess) onSuccess();

        } catch (e) {
            error = e instanceof Error ? e.message : 'Error al guardar la conversión';
        } 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="space-y-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">
                <div class="grid grid-cols-4 items-center gap-4">
                    <Label for="from_code" class="text-right">De Unidad <span class="text-destructive">*</span></Label>
                    <div class="col-span-3">
                        <Input 
                            id="from_code" 
                            bind:value={formData.from_unit_code} 
                            placeholder="Ej: KGM" 
                            maxlength={5} 
                            disabled={loading}
                        />
                        <p class="text-[10px] text-muted-foreground mt-1">Código de la unidad origen.</p>
                    </div>
                </div>

                <div class="grid grid-cols-4 items-center gap-4">
                    <Label for="to_code" class="text-right">A Unidad <span class="text-destructive">*</span></Label>
                    <div class="col-span-3">
                        <Input 
                            id="to_code" 
                            bind:value={formData.to_unit_code} 
                            placeholder="Ej: LBR" 
                            maxlength={5} 
                            disabled={loading}
                        />
                        <p class="text-[10px] text-muted-foreground mt-1">Código de la unidad destino.</p>
                    </div>
                </div>

                <div class="grid grid-cols-4 items-center gap-4">
                    <Label for="factor" class="text-right">Factor <span class="text-destructive">*</span></Label>
                    <div class="col-span-3">
                        <Input 
                            id="factor" 
                            type="number"
                            step="0.000001"
                            bind:value={formData.conversion_factor} 
                            placeholder="Ej: 2.20462" 
                            disabled={loading}
                        />
                        <p class="text-[10px] text-muted-foreground mt-1">Numeric(13, 6).</p>
                    </div>
                </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>