<script setup>
import { ref, watch, computed } from 'vue';
import { formatCurrency } from '@/utils/formatters';
import { useForm, useApi, apiURL } from '@Services/Api';

import Modal from '@Holos/Modal.vue';
import FormInput from '@Holos/Form/Input.vue';
import FormError from '@Holos/Form/Elements/Error.vue';
import GoogleIcon from '@Shared/GoogleIcon.vue';
import SerialInputList from '@Components/POS/SerialInputList.vue';
import SerialSelector from '@Components/POS/SerialSelector.vue';

/** Eventos */
const emit = defineEmits(['close', 'updated']);

/** Propiedades */
const props = defineProps({
    show: Boolean,
    movement: Object
});

/** Estado */
const warehouses = ref([]);
const suppliers = ref([]);
const loading = ref(false);
const serialsText = ref('');
const showSerialSelector = ref(false);
const selectedSerialObjects = ref([]);
const api = useApi();

/** Formulario */
const form = useForm({
    quantity: 0,
    unit_cost: 0,
    warehouse_id: '',
    supplier_id: null,
    origin_warehouse_id: '',
    destination_warehouse_id: '',
    invoice_reference: '',
    notes: '',
    serial_numbers: [] // Array de números de serie
});

/** Estado para manejo de seriales */
const serialsList = ref([]); // Array de { serial_number, locked }

/** Computed */
const movementTypeInfo = computed(() => {
    const types = {
        entry: {
            label: 'Entrada',
            icon: 'add_circle',
            color: 'green',
            bgClass: 'bg-green-100 dark:bg-green-900/30',
            textClass: 'text-green-800 dark:text-green-300'
        },
        exit: {
            label: 'Salida',
            icon: 'remove_circle',
            color: 'red',
            bgClass: 'bg-red-100 dark:bg-red-900/30',
            textClass: 'text-red-800 dark:text-red-300'
        },
        transfer: {
            label: 'Traspaso',
            icon: 'swap_horiz',
            color: 'blue',
            bgClass: 'bg-blue-100 dark:bg-blue-900/30',
            textClass: 'text-blue-800 dark:text-blue-300'
        },
    };
    return types[props.movement?.movement_type] || types.entry;
});

const totalCost = computed(() => {
    return form.quantity * form.unit_cost;
});

const allowsDecimals = computed(() => {
    return props.movement?.inventory?.unit_of_measure?.allows_decimals || false;
});

const hasSerials = computed(() => {
    return props.movement?.inventory?.track_serials || false;
});

const serialsArray = computed(() => {
    return serialsList.value
        .map(s => s.serial_number.trim())
        .filter(s => s.length > 0);
});

// Si tiene seriales y no permite decimales, la cantidad se controla por seriales
const quantityLockedBySerials = computed(() => {
    return hasSerials.value && !allowsDecimals.value;
});

const serialsValidation = computed(() => {
    if (!hasSerials.value) return { valid: true, message: '' };

    const quantity = Number(form.quantity);
    const serialCount = serialsArray.value.length;

    if (quantity > 0 && serialCount === 0) {
        return { valid: false, message: 'Debe ingresar números de serie' };
    }

    if (serialCount !== quantity) {
        return {
            valid: false,
            message: `Debe ingresar ${quantity} número(s) de serie (actual: ${serialCount})`
        };
    }

    // Verificar duplicados
    const uniqueSerials = new Set(serialsArray.value);
    if (uniqueSerials.size !== serialCount) {
        return { valid: false, message: 'Hay números de serie duplicados' };
    }

    return { valid: true, message: '' };
});

// Actualizar cantidad automáticamente cuando cambian los seriales
const updateQuantityFromSerials = () => {
    if (!quantityLockedBySerials.value) return;
    const count = serialsArray.value.length;
    form.quantity = count > 0 ? count : 1;
};

// Seriales pre-seleccionados para SerialSelector (objetos completos con id)
const serialSelectorPreSelected = computed(() => selectedSerialObjects.value);

/** Métodos de selección de seriales (para traspasos y salidas) */
const openSerialSelector = () => {
    showSerialSelector.value = true;
};

const handleSerialsConfirmed = ({ serials, serialNumbers }) => {
    selectedSerialObjects.value = serials;
    serialsList.value = serialNumbers.map(sn => ({ serial_number: sn, locked: false }));
    updateQuantityFromSerials();
    showSerialSelector.value = false;
};

/** Métodos */
const loadWarehouses = () => {
    loading.value = true;
    Promise.all([
        api.get(apiURL('almacenes'), {
            onSuccess: (data) => {
                warehouses.value = data.warehouses?.data || data.data || [];

                if (props.movement?.movement_type === 'entry' && !form.destination_warehouse_id) {
                const mainWarehouse = warehouses.value.find(w => w.is_main || w.is_principal);
                if (mainWarehouse) {
                    form.destination_warehouse_id = mainWarehouse.id;
                }
            }
            }
        }),
        api.get(apiURL('proveedores'), {
            onSuccess: (data) => {
                suppliers.value = data.suppliers?.data || data.suppliers || [];
            }
        })
    ]).finally(() => {
        loading.value = false;
    });
};

const updateMovement = () => {
    // Validar seriales si el producto los requiere
    if (hasSerials.value && !serialsValidation.value.valid) {
        window.Notify.warning(serialsValidation.value.message);
        return;
    }

    // Preparar datos según el tipo de movimiento
    const data = {
        quantity: Number(form.quantity),  // Común para todos los tipos
        notes: form.notes || null
    };

    // Siempre enviar serial_numbers si el producto requiere seriales
    if (hasSerials.value) {
        // Validar que haya seriales
        if (serialsArray.value.length === 0) {
            window.Notify.warning('Debe ingresar números de serie para este producto');
            return;
        }
        data.serial_numbers = serialsArray.value;
    }

    // Campos específicos por tipo
    if (props.movement.movement_type === 'entry') {
        data.unit_cost = Number(form.unit_cost);
        data.warehouse_to_id = form.destination_warehouse_id;
        data.supplier_id = form.supplier_id || null;
        data.invoice_reference = form.invoice_reference || null;
    } else if (props.movement.movement_type === 'exit') {
        data.warehouse_from_id = form.origin_warehouse_id;
    } else if (props.movement.movement_type === 'transfer') {
        data.warehouse_from_id = form.origin_warehouse_id;
        data.warehouse_to_id = form.destination_warehouse_id;
    }

    api.put(apiURL(`movimientos/${props.movement.id}`), {
        data,
        onSuccess: () => {
            window.Notify.success('Movimiento actualizado correctamente');
            emit('updated');
            closeModal();
        },
        onFail: (response) => {
            window.Notify.error(response.message || 'Error al actualizar el movimiento');
        },
        onError: () => {
            window.Notify.error('Error al actualizar el movimiento');
        }
    });
};

const closeModal = () => {
    form.reset();
    showSerialSelector.value = false;
    emit('close');
};

/** Helpers */
const applySerials = (movement) => {
    const isTransfer = movement.movement_type === 'transfer';
    const isExit = movement.movement_type === 'exit';
    const rawSerials = isTransfer
        ? (movement.transferred_serials || [])
        : isExit
            ? (movement.exited_serials || [])
            : (movement.serials || []);

    if (isTransfer || isExit) {
        selectedSerialObjects.value = rawSerials;
    }

    if (rawSerials.length > 0) {
        const movementWarehouseId = movement.warehouse_to?.id || movement.warehouse_to_id;

        serialsList.value = rawSerials.map(s => {
            let locked = false;
            let lock_reason = null;

            const isOwnExitSerial = isExit && s.status === 'salida';

            if (!isOwnExitSerial && s.status !== 'disponible') {
                locked = true;
                lock_reason = s.status;
            } else if (
                !isTransfer && !isExit &&
                s.warehouse_id &&
                movementWarehouseId &&
                s.warehouse_id !== movementWarehouseId
            ) {
                locked = true;
                lock_reason = 'traspasado';
            }

            return { serial_number: s.serial_number, locked, lock_reason };
        });
    } else {
        serialsList.value = [{ serial_number: '', locked: false }];
    }
};

/** Observadores */
watch(() => props.show, (isShown) => {
    if (isShown) {
        loadWarehouses();

        if (props.movement) {
            // Cargar datos básicos del formulario desde el prop
            form.quantity = props.movement.quantity || 0;
            form.unit_cost = props.movement.unit_cost || 0;
            form.invoice_reference = props.movement.invoice_reference || '';
            form.notes = props.movement.notes || '';
            form.supplier_id = props.movement.supplier_id || null;

            // Almacenes según tipo
            if (props.movement.movement_type === 'entry') {
                form.destination_warehouse_id = props.movement.warehouse_to_id || props.movement.warehouse_to?.id || '';
            } else if (props.movement.movement_type === 'exit') {
                form.origin_warehouse_id = props.movement.warehouse_from_id || props.movement.warehouse_from?.id || '';
            } else if (props.movement.movement_type === 'transfer') {
                form.origin_warehouse_id = props.movement.warehouse_from_id || props.movement.warehouse_from?.id || '';
                form.destination_warehouse_id = props.movement.warehouse_to_id || props.movement.warehouse_to?.id || '';
            }

            // Limpiar seriales mientras se carga el detalle
            serialsList.value = [{ serial_number: '', locked: false }];
            selectedSerialObjects.value = [];

            // Obtener el movimiento completo con seriales desde el endpoint de detalle
            api.get(apiURL(`movimientos/${props.movement.id}`), {
                onSuccess: (data) => {
                    applySerials(data.movement);
                }
            });
        }
    } else {
        // Limpiar al cerrar
        serialsText.value = '';
    }
}, { immediate: true });
</script>

<template>
    <Modal :show="show" max-width="lg" @close="closeModal">
        <div class="p-6">
            <!-- Header -->
            <div class="flex items-center justify-between mb-6">
                <div class="flex items-center gap-3">
                    <div
                        :class="[
                            'flex items-center justify-center w-10 h-10 rounded-full',
                            movementTypeInfo.bgClass
                        ]"
                    >
                        <GoogleIcon :name="movementTypeInfo.icon" :class="['text-xl', movementTypeInfo.textClass]" />
                    </div>
                    <div>
                        <h3 class="text-lg font-bold text-gray-900 dark:text-gray-100">
                            Editar {{ movementTypeInfo.label }}
                        </h3>
                        <p class="text-xs text-gray-500 dark:text-gray-400">
                            Movimiento #{{ movement?.id }}
                        </p>
                    </div>
                </div>
                <button
                    @click="closeModal"
                    class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
                >
                    <GoogleIcon name="close" class="text-xl" />
                </button>
            </div>

            <!-- Información del producto -->
            <div class="mb-4 p-3 bg-gray-50 dark:bg-gray-800/50 border border-gray-200 dark:border-gray-700 rounded-lg">
                <div class="flex items-center gap-2 mb-1">
                    <GoogleIcon name="inventory_2" class="text-gray-500 dark:text-gray-400 text-sm" />
                    <p class="text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase">Producto</p>
                    <span
                        v-if="hasSerials"
                        class="ml-auto px-2 py-0.5 text-xs font-semibold bg-amber-100 dark:bg-amber-900/30 text-amber-700 dark:text-amber-300 rounded-full flex items-center gap-1"
                    >
                        <GoogleIcon name="qr_code_scanner" class="text-xs" />
                        Con seriales
                    </span>
                </div>
                <p class="text-sm font-semibold text-gray-900 dark:text-gray-100">
                    {{ movement?.inventory?.name || 'N/A' }}
                </p>
                <p class="text-xs text-gray-500 dark:text-gray-400">
                    SKU: {{ movement?.inventory?.sku || 'N/A' }}
                </p>
            </div>

            <!-- Formulario -->
            <form @submit.prevent="updateMovement" class="space-y-4">
                <div class="space-y-4">
                    <!-- Cantidad -->
                    <div>
                        <label class="block text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-1.5">
                            CANTIDAD
                        </label>
                        <FormInput
                            v-model="form.quantity"
                            type="number"
                            min="1"
                            step="1"
                            placeholder="0"
                            :disabled="quantityLockedBySerials"
                            required
                        />
                        <p v-if="quantityLockedBySerials" class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                            Controlado por seriales
                        </p>
                        <FormError :message="form.errors?.quantity" />
                    </div>

                    <!-- Números de Serie: traspasos y salidas usan selector -->
                    <div
                        v-if="hasSerials && (movement?.movement_type === 'transfer' || movement?.movement_type === 'exit')"
                        class="p-3 bg-blue-50 dark:bg-blue-900/10 border border-blue-200 dark:border-blue-800 rounded-lg"
                    >
                        <div class="flex items-center justify-between gap-2">
                            <div class="flex items-center gap-2 flex-1">
                                <GoogleIcon name="qr_code_2" class="text-blue-600 dark:text-blue-400 text-lg" />
                                <div>
                                    <p class="text-xs font-semibold text-blue-900 dark:text-blue-100">
                                        Este producto requiere números de serie
                                    </p>
                                    <p class="text-xs text-blue-700 dark:text-blue-300">
                                        {{ serialsArray.length }} serial(es) seleccionado(s)
                                    </p>
                                </div>
                            </div>
                            <button
                                type="button"
                                @click="openSerialSelector"
                                class="flex items-center gap-1 px-3 py-1.5 text-xs font-semibold text-white bg-blue-600 hover:bg-blue-700 rounded transition-colors"
                            >
                                <GoogleIcon name="qr_code_scanner" class="text-sm" />
                                {{ serialsArray.length > 0 ? 'Cambiar' : 'Seleccionar' }}
                            </button>
                        </div>
                        <!-- Badges de seriales seleccionados -->
                        <div v-if="serialsArray.length > 0" class="mt-2 pt-2 border-t border-blue-200 dark:border-blue-800">
                            <p class="text-xs font-medium text-blue-900 dark:text-blue-100 mb-1">Seriales seleccionados:</p>
                            <div class="flex flex-wrap gap-1">
                                <span
                                    v-for="(serial, idx) in serialsArray.slice(0, 5)"
                                    :key="idx"
                                    class="inline-flex items-center px-2 py-0.5 text-xs font-mono bg-blue-100 dark:bg-blue-900/30 text-blue-800 dark:text-blue-200 rounded"
                                >
                                    {{ serial }}
                                </span>
                                <span
                                    v-if="serialsArray.length > 5"
                                    class="inline-flex items-center px-2 py-0.5 text-xs bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 rounded"
                                >
                                    +{{ serialsArray.length - 5 }} más
                                </span>
                            </div>
                        </div>
                        <!-- Validación -->
                        <div v-if="serialsArray.length > 0" class="mt-2 flex items-center justify-end">
                            <p v-if="!serialsValidation.valid" class="text-xs text-red-600 dark:text-red-400 font-medium">
                                {{ serialsValidation.message }}
                            </p>
                            <p v-else class="text-xs text-green-600 dark:text-green-400 font-medium flex items-center gap-1">
                                <GoogleIcon name="check_circle" class="text-sm" />
                                Válido
                            </p>
                        </div>
                    </div>

                    <!-- Números de Serie: entradas usan lista de inputs -->
                    <div v-else-if="hasSerials" class="bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg p-4">
                        <div class="flex items-center gap-2 mb-2">
                            <GoogleIcon name="qr_code_scanner" class="text-amber-600 dark:text-amber-400" />
                            <label class="text-xs font-semibold text-amber-700 dark:text-amber-300 uppercase">
                                NÚMEROS DE SERIE
                            </label>
                        </div>
                        <SerialInputList
                            v-model="serialsList"
                            @update:model-value="updateQuantityFromSerials"
                        />
                        <!-- Validación -->
                        <div class="mt-2 flex items-center justify-between">
                            <p class="text-xs text-amber-600 dark:text-amber-400">
                                <span class="font-semibold">{{ serialsArray.length }}</span> de {{ form.quantity }} seriales
                            </p>
                            <p
                                v-if="!serialsValidation.valid && serialsArray.length > 0"
                                class="text-xs text-red-600 dark:text-red-400 font-medium"
                            >
                                {{ serialsValidation.message }}
                            </p>
                            <p
                                v-else-if="serialsValidation.valid && serialsArray.length > 0"
                                class="text-xs text-green-600 dark:text-green-400 font-medium flex items-center gap-1"
                            >
                                <GoogleIcon name="check_circle" class="text-sm" />
                                Válido
                            </p>
                        </div>
                    </div>

                    <!-- Costo unitario (solo para entradas) -->
                    <div v-if="movement?.movement_type === 'entry'">
                        <label class="block text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-1.5">
                            COSTO UNITARIO
                        </label>
                        <FormInput
                            v-model="form.unit_cost"
                            type="number"
                            min="0"
                            step="0.01"
                            placeholder="0.00"
                                                        required
                        />
                        <FormError :message="form.errors?.unit_cost" />

                        <!-- Mostrar costo total -->
                        <p v-if="form.quantity && form.unit_cost" class="mt-1.5 text-xs text-gray-600 dark:text-gray-400">
                            Costo total:
                            <span class="font-semibold text-gray-900 dark:text-gray-100">
                                {{ formatCurrency(totalCost) }}
                            </span>
                        </p>
                    </div>

                    <!-- Almacén destino (para entradas) -->
                    <div v-if="movement?.movement_type === 'entry'">
                        <label class="block text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-1.5">
                            ALMACÉN DESTINO
                        </label>
                        <select
                            v-model="form.destination_warehouse_id"
                            class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 text-sm focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 disabled:opacity-50 disabled:cursor-not-allowed"
                            required
                            disabled
                        >
                            <option value="">Seleccionar almacén...</option>
                            <option v-for="wh in warehouses" :key="wh.id" :value="wh.id">
                                {{ wh.name }} ({{ wh.code }})
                            </option>
                        </select>
                        <FormError :message="form.errors?.warehouse_id" />
                    </div>

                    <!-- Almacén origen (para salidas) -->
                    <div v-if="movement?.movement_type === 'exit'">
                        <label class="block text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-1.5">
                            ALMACÉN ORIGEN
                        </label>
                        <select
                            v-model="form.origin_warehouse_id"
                            class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 text-sm focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 disabled:opacity-50 disabled:cursor-not-allowed"
                            disabled
                            required
                        >
                            <option value="">Seleccionar almacén...</option>
                            <option v-for="wh in warehouses" :key="wh.id" :value="wh.id">
                                {{ wh.name }} ({{ wh.code }})
                            </option>
                        </select>
                        <FormError :message="form.errors?.warehouse_id" />
                    </div>

                    <!-- Almacenes origen y destino (para traspasos) -->
                    <div v-if="movement?.movement_type === 'transfer'" class="grid grid-cols-2 gap-3">
                        <div>
                            <label class="block text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-1.5">
                                ALMACÉN ORIGEN
                            </label>
                            <select
                                v-model="form.origin_warehouse_id"
                                class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 text-sm focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 disabled:opacity-50 disabled:cursor-not-allowed"
                                disabled
                                required
                            >
                                <option value="">Seleccionar...</option>
                                <option
                                    v-for="wh in warehouses"
                                    :key="wh.id"
                                    :value="wh.id"
                                >
                                    {{ wh.name }} ({{ wh.code }})
                                </option>
                            </select>
                            <FormError :message="form.errors?.origin_warehouse_id" />
                        </div>
                        <div>
                            <label class="block text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-1.5">
                                ALMACÉN DESTINO
                            </label>
                            <select
                                v-model="form.destination_warehouse_id"
                                class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 text-sm focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 disabled:opacity-50 disabled:cursor-not-allowed"
                                required
                                disabled
                            >
                                <option value="">Seleccionar...</option>
                                <option
                                    v-for="wh in warehouses"
                                    :key="wh.id"
                                    :value="wh.id"
                                    :disabled="wh.id === form.origin_warehouse_id"
                                >
                                    {{ wh.name }} ({{ wh.code }})
                                </option>
                            </select>
                            <FormError :message="form.errors?.destination_warehouse_id" />
                        </div>
                    </div>

                    <!-- Proveedor y Referencia (solo para entradas) -->
                    <div v-if="movement?.movement_type === 'entry'" class="space-y-4">
                        <!-- Proveedor (solo lectura) -->
                        <div>
                            <label class="block text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-1.5">
                                PROVEEDOR
                            </label>
                            <div class="w-full px-3 py-2 border border-gray-200 dark:border-gray-700 rounded-lg bg-gray-50 dark:bg-gray-900 text-sm text-gray-600 dark:text-gray-400 cursor-not-allowed">
                                {{ movement?.supplier?.business_name || 'Sin proveedor' }}
                            </div>
                        </div>

                        <!-- Referencia de factura -->
                        <div>
                            <label class="block text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-1.5">
                                REFERENCIA DE FACTURA
                            </label>
                            <FormInput
                                v-model="form.invoice_reference"
                                type="text"
                                placeholder="Ej: FAC-2026-001"
                            />
                            <FormError :message="form.errors?.invoice_reference" />
                        </div>
                    </div>

                    <!-- Notas -->
                    <div>
                        <label class="block text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-1.5">
                            NOTAS <span class="text-gray-400 text-xs normal-case">(opcional)</span>
                        </label>
                        <textarea
                            v-model="form.notes"
                            rows="2"
                            placeholder="Notas adicionales..."
                                                        class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 text-sm focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 resize-none disabled:opacity-50 disabled:cursor-not-allowed"
                        ></textarea>
                        <FormError :message="form.errors?.notes" />
                    </div>
                </div>

                <!-- Botones -->
                <div class="flex items-center justify-end gap-3 mt-6 pt-4 border-t border-gray-200 dark:border-gray-700">
                    <button
                        type="button"
                        @click="closeModal"
                        class="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition-colors"
                    >
                        Cancelar
                    </button>
                    <button
                        type="submit"
                        :disabled="form.processing"
                        class="flex items-center gap-2 px-4 py-2 text-sm font-semibold text-white rounded-lg focus:outline-none focus:ring-2 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                        :class="{
                            'bg-green-600 hover:bg-green-700 focus:ring-green-600': movement?.movement_type === 'entry',
                            'bg-red-600 hover:bg-red-700 focus:ring-red-600': movement?.movement_type === 'exit',
                            'bg-blue-600 hover:bg-blue-700 focus:ring-blue-600': movement?.movement_type === 'transfer'
                        }"
                    >
                        <GoogleIcon name="check_circle" class="text-lg" />
                        <span v-if="form.processing">Actualizando...</span>
                        <span v-else>Actualizar Movimiento</span>
                    </button>
                </div>
            </form>
        </div>

        <!-- Selector de seriales (para traspasos y salidas) -->
        <SerialSelector
            v-if="movement?.inventory && showSerialSelector"
            :show="showSerialSelector"
            :product="{ id: movement.inventory?.id || movement.inventory_id, name: movement.inventory?.name, sku: movement.inventory?.sku, track_serials: movement.inventory?.track_serials }"
            :warehouse-id="Number(form.origin_warehouse_id) || null"
            :pre-selected-serials="serialSelectorPreSelected"
            @close="showSerialSelector = false"
            @confirm="handleSerialsConfirmed"
        />
    </Modal>
</template>
