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

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 SerialSelector from '@Components/POS/SerialSelector.vue';

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

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

/** Estado */
const products = ref([]);
const warehouses = ref([]);
const loading = ref(false);
const selectedProducts = ref([]);
const warehouseFromStock = ref(null);

const api = useApi();

// Estado para búsqueda de productos
let debounceTimer = null;
const productSearch = ref('');
const searchingProduct = ref(false);
const productNotFound = ref(false);
const productSuggestions = ref([]);
const showProductSuggestions = ref(false);
const currentSearchIndex = ref(null); // Índice del producto que se está buscando

// Estado para selección de seriales
const showSerialSelector = ref(false);
const currentProductForSerials = ref(null);
const currentProductIndex = ref(null);

/** Formulario */
const form = useForm({
    warehouse_id: '',
    reference: '',
    notes: '',
    products: []
});

/** Computed */
const totalQuantity = computed(() => {
    return selectedProducts.value.reduce((sum, item) => sum + Number(item.quantity), 0);
});

const totalCost = computed(() => {
    return selectedProducts.value.reduce((sum, item) => {
        return sum + (item.quantity * (item.unit_cost || 0));
    }, 0);
});

// Determina si un producto puede usar seriales (no puede si la unidad permite decimales)
const canUseSerials = (item) => {
    if (!item.unit_of_measure) return true;
    return !item.allows_decimals;
};

/** Métodos */
const loadData = () => {
    loading.value = true;

    api.get(apiURL('almacenes'), {
        onSuccess: (data) => {
            warehouses.value = data.warehouses?.data || data.data || [];
        },
        onFinish: () => {
            loading.value = false;
        }
    });
};

const loadProducts = (warehouseId) => {
    if (!warehouseId) {
        products.value = [];
        warehouseFromStock.value = null;
        return;
    }

    loading.value = true;

    api.get(apiURL(`inventario/almacen/${warehouseId}`), {
        onSuccess: (data) => {
            const productList = data.products || [];
            products.value = productList;
            warehouseFromStock.value = productList.length;
        },
        onFinish: () => {
            loading.value = false;
        }
    });
};

const addProduct = () => {
    selectedProducts.value.push({
        inventory_id: '',
        product_name: '',
        product_sku: '',
        quantity: 1,
        unit_cost: 0,
        track_serials: false,
        unit_of_measure: null,
        allows_decimals: false,
        selected_serials: [], // Array de números de serie seleccionados
        available_serials_count: 0
    });
};

const removeProduct = (index) => {
    selectedProducts.value.splice(index, 1);
};

/** Métodos de búsqueda de productos */
const onProductInput = (index) => {
    currentSearchIndex.value = index;
    productNotFound.value = false;

    const searchValue = productSearch.value?.trim();
    if (!searchValue || searchValue.length < 2) {
        productSuggestions.value = [];
        showProductSuggestions.value = false;
        return;
    }

    clearTimeout(debounceTimer);
    debounceTimer = setTimeout(() => {
        showProductSuggestions.value = true;
        searchProduct();
    }, 300);
};

const searchProduct = () => {
    const searchValue = productSearch.value?.trim();
    if (!searchValue) {
        productSuggestions.value = [];
        showProductSuggestions.value = false;
        return;
    }

    // Validar que haya un almacén de origen seleccionado
    if (!form.warehouse_id) {
        productSuggestions.value = [];
        showProductSuggestions.value = false;
        productNotFound.value = true;
        window.Notify.warning('Primero selecciona el almacén de origen');
        return;
    }

    searchingProduct.value = true;
    productNotFound.value = false;

    api.get(apiURL(`inventario/almacen/${form.warehouse_id}?q=${encodeURIComponent(searchValue)}`), {
        onSuccess: (data) => {
            const foundProducts = data.products?.data || data.data || data.products || [];
            if (foundProducts.length > 0) {
                productSuggestions.value = foundProducts;
                showProductSuggestions.value = true;
            } else {
                productSuggestions.value = [];
                showProductSuggestions.value = false;
                productNotFound.value = true;
            }
        },
        onFail: (data) => {
            productSuggestions.value = [];
            showProductSuggestions.value = false;
            productNotFound.value = true;
            window.Notify.error(data.message || 'Error al buscar producto');
        },
        onError: () => {
            productSuggestions.value = [];
            showProductSuggestions.value = false;
            productNotFound.value = true;
        },
        onFinish: () => {
            searchingProduct.value = false;
        }
    });
};

const selectProduct = (product) => {
    if (currentSearchIndex.value !== null) {
        selectedProducts.value[currentSearchIndex.value].inventory_id = product.id;
        selectedProducts.value[currentSearchIndex.value].product_name = product.name;
        selectedProducts.value[currentSearchIndex.value].product_sku = product.sku;
        selectedProducts.value[currentSearchIndex.value].track_serials = product.track_serials || false;
        selectedProducts.value[currentSearchIndex.value].available_serials_count = product.warehouse_stock || 0;
        selectedProducts.value[currentSearchIndex.value].unit_of_measure = product.unit_of_measure || null;
        selectedProducts.value[currentSearchIndex.value].allows_decimals = product.unit_of_measure?.allows_decimals || false;

        // Limpiar seriales si la unidad permite decimales
        if (product.unit_of_measure?.allows_decimals) {
            selectedProducts.value[currentSearchIndex.value].selected_serials = [];
        }
    }

    productSearch.value = '';
    productSuggestions.value = [];
    showProductSuggestions.value = false;
    productNotFound.value = false;
    currentSearchIndex.value = null;

    window.Notify.success(`Producto ${product.name} agregado`);
};

// Gestión de seriales
const openSerialSelector = (item, index) => {
    // Crear objeto compatible con SerialSelector (necesita 'id' no 'inventory_id')
    currentProductForSerials.value = {
        id: item.inventory_id,
        name: item.product_name,
        sku: item.product_sku,
        track_serials: item.track_serials
    };
    currentProductIndex.value = index;
    showSerialSelector.value = true;
};

const closeSerialSelector = () => {
    showSerialSelector.value = false;
    currentProductForSerials.value = null;
    currentProductIndex.value = null;
};

const handleSerialsConfirmed = ({ serialNumbers, quantity }) => {
    if (currentProductIndex.value !== null) {
        selectedProducts.value[currentProductIndex.value].selected_serials = serialNumbers;
        selectedProducts.value[currentProductIndex.value].quantity = quantity;
    }
    closeSerialSelector();
};

const createExit = () => {
    // Validar que productos con seriales (y que pueden usarlos) tengan seriales seleccionados
    const invalidProducts = selectedProducts.value.filter(
        item => item.track_serials && canUseSerials(item) && (!item.selected_serials || item.selected_serials.length === 0)
    );

    if (invalidProducts.length > 0) {
        window.Notify.error('Debes seleccionar los números de serie para los productos que lo requieren');
        return;
    }

    // Preparar datos del formulario
    form.products = selectedProducts.value.map(item => {
        const productData = {
            inventory_id: item.inventory_id,
            quantity: Number(item.quantity),
            serial_numbers: [] // Inicializar siempre como array vacío
        };

        // Agregar seriales solo si la unidad lo permite y hay seriales seleccionados
        if (item.track_serials && canUseSerials(item) && item.selected_serials && item.selected_serials.length > 0) {
            productData.serial_numbers = item.selected_serials;
        }

        return productData;
    });

    form.post(apiURL('movimientos/salida'), {
        data: {
            warehouse_id: form.warehouse_id,
            reference: form.reference,
            notes: form.notes,
            products: form.products
        },
        onSuccess: () => {
            window.Notify.success('Salida registrada correctamente');
            emit('created');
            closeModal();
        },
        onFail: (data) => {
            window.Notify.error(data.message || 'Error al registrar la salida');
        },
        onError: () => {
            window.Notify.error('Error al registrar la salida');
        }
    });
};

const closeModal = () => {
    form.reset();
    selectedProducts.value = [];
    productSearch.value = '';
    productSuggestions.value = [];
    showProductSuggestions.value = false;
    productNotFound.value = false;
    currentSearchIndex.value = null;
    emit('close');
};

/** Watchers */
watch(() => props.show, (isShown) => {
    if (isShown) {
        loadData();
        if (selectedProducts.value.length === 0) {
            addProduct();
        }
    }
});

// Cargar productos cuando se selecciona un almacén de origen
watch(() => form.warehouse_id, (newWarehouseId, oldWarehouseId) => {
    if (newWarehouseId !== oldWarehouseId) {
        loadProducts(newWarehouseId);

        // Limpiar productos seleccionados si había alguno y se cambió el almacén
        if (oldWarehouseId && selectedProducts.value.length > 0) {
            selectedProducts.value = [];
            addProduct();
        }
    }
});
</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 bg-red-100 dark:bg-red-900/30">
                        <GoogleIcon name="remove_circle" class="text-xl text-red-600 dark:text-red-400" />
                    </div>
                    <h3 class="text-lg font-bold text-gray-900 dark:text-gray-100">
                        Registrar Salida
                    </h3>
                </div>
                <button
                    @click="closeModal"
                    class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
                >
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                    </svg>
                </button>
            </div>

            <!-- Formulario -->
            <form @submit.prevent="createExit" class="space-y-4">
                <div class="space-y-4">
                    <!-- Almacén origen -->
                    <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.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"
                        >
                            <option value="">Seleccionar almacén...</option>
                            <option v-for="wh in warehouses" :key="wh.id" :value="wh.id">
                                {{ wh.name }} ({{ wh.code }})
                            </option>
                        </select>
                        <p v-if="warehouseFromStock !== null" class="mt-1 text-xs text-gray-600 dark:text-gray-400">
                            <span v-if="warehouseFromStock > 0" class="text-green-600 dark:text-green-400">
                                ✓ {{ warehouseFromStock }} producto(s) en inventario
                            </span>
                            <span v-else class="text-amber-600 dark:text-amber-400">
                                ⚠ Sin productos en inventario
                            </span>
                        </p>
                        <FormError :message="form.errors?.warehouse_id" />
                    </div>

                     <!-- Lista de productos -->
                    <div>
                        <div class="flex items-center justify-between mb-2">
                            <label class="block text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase">
                                PRODUCTOS
                            </label>
                            <button
                            type="button"
                            @click="addProduct"
                            class="flex items-center gap-1 px-2 py-1 text-xs font-medium text-indigo-600 dark:text-indigo-400 hover:bg-indigo-50 dark:hover:bg-indigo-900/30 rounded transition-colors"
                            >
                            <GoogleIcon name="add" class="text-sm" />
                            Agregar producto
                        </button>
                        </div>

                        <div class="space-y-3">
                            <div
                                v-for="(item, index) in selectedProducts"
                                :key="index"
                                class="p-3 border border-gray-200 dark:border-gray-700 rounded-lg bg-gray-50 dark:bg-gray-800/50"
                            >
                                <div class="grid grid-cols-12 gap-3 items-start">
                                    <!-- Producto -->
                                    <div class="col-span-12 sm:col-span-5">
                                        <label class="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">
                                            Producto
                                        </label>
                                        <!-- Si ya se seleccionó un producto -->
                                        <div v-if="item.inventory_id && item.product_name" class="flex items-center gap-2 px-2 py-1.5 bg-indigo-50 dark:bg-indigo-900/20 border border-indigo-200 dark:border-indigo-800 rounded text-sm">
                                            <div class="flex-1 min-w-0">
                                                <p class="text-sm font-semibold text-gray-900 dark:text-gray-100 truncate">
                                                    {{ item.product_name }}
                                                </p>
                                                <p class="text-xs text-gray-500 dark:text-gray-400">{{ item.product_sku }}</p>
                                            </div>
                                            <button
                                                type="button"
                                                @click="item.inventory_id = ''; item.product_name = ''; item.product_sku = ''"
                                                class="text-gray-500 hover:text-gray-700 dark:hover:text-gray-300"
                                            >
                                                <GoogleIcon name="close" class="text-sm" />
                                            </button>
                                        </div>
                                        <!-- Input de búsqueda -->
                                        <div v-else class="relative">
                                            <input
                                                v-model="productSearch"
                                                @input="onProductInput(index)"
                                                @focus="() => { currentSearchIndex = index; productSuggestions.length > 0 && (showProductSuggestions = true); }"
                                                type="text"
                                                placeholder="Buscar por código de barras o nombre..."
                                                class="w-full px-2 py-1.5 pr-8 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                                                :class="{
                                                    'border-red-500 focus:ring-red-500 focus:border-red-500': productNotFound && currentSearchIndex === index
                                                }"
                                                :disabled="searchingProduct"
                                            />
                                            <div v-if="searchingProduct && currentSearchIndex === index" class="absolute right-2 top-1/2 -translate-y-1/2">
                                                <GoogleIcon name="hourglass_empty" class="text-sm text-gray-400 animate-spin" />
                                            </div>
                                            <div v-else-if="productSearch && currentSearchIndex === index" class="absolute right-2 top-1/2 -translate-y-1/2">
                                                <GoogleIcon name="search" class="text-sm text-gray-400" />
                                            </div>
                                            <!-- Dropdown de sugerencias -->
                                            <div
                                                v-if="showProductSuggestions && productSuggestions.length > 0 && currentSearchIndex === index"
                                                class="absolute z-50 w-full mt-1 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg max-h-48 overflow-y-auto"
                                            >
                                                <button
                                                    v-for="product in productSuggestions"
                                                    :key="product.id"
                                                    type="button"
                                                    @click="selectProduct(product)"
                                                    class="w-full flex items-center gap-2 px-3 py-2 hover:bg-indigo-50 dark:hover:bg-indigo-900/20 transition-colors text-left border-b border-gray-100 dark:border-gray-700 last:border-b-0"
                                                >
                                                    <div class="flex-1 min-w-0">
                                                        <p class="text-sm font-semibold text-gray-900 dark:text-gray-100 truncate">
                                                            {{ product.name }}
                                                        </p>
                                                        <p class="text-xs text-gray-500 dark:text-gray-400">
                                                            SKU: {{ product.sku }}
                                                        </p>
                                                    </div>
                                                </button>
                                            </div>
                                            <!-- Error de producto no encontrado -->
                                            <div v-if="productNotFound && currentSearchIndex === index" class="absolute z-50 w-full mt-1">
                                                <div class="flex items-start gap-1 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded p-2">
                                                    <GoogleIcon name="error" class="text-red-600 dark:text-red-400 text-sm shrink-0" />
                                                    <p class="text-xs text-red-800 dark:text-red-300">
                                                        Producto no encontrado
                                                    </p>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Cantidad -->
                                    <div class="col-span-5 sm:col-span-3">
                                        <label class="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">
                                            Cantidad
                                        </label>
                                        <input
                                            v-model="item.quantity"
                                            type="number"
                                            min="1"
                                            step="1"
                                            placeholder="0"
                                            :disabled="item.track_serials && canUseSerials(item)"
                                            class="w-full px-2 py-1.5 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 disabled:opacity-50 disabled:cursor-not-allowed"
                                        />
                                        <p v-if="item.track_serials && canUseSerials(item)" class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                                            Controlado por seriales
                                        </p>
                                    </div>

                                    <!-- Botón eliminar -->
                                    <div class="col-span-2 sm:col-span-1">
                                        <label class="block text-xs font-medium text-transparent mb-1">.</label>
                                        <button
                                            type="button"
                                            @click="removeProduct(index)"
                                            :disabled="selectedProducts.length === 1"
                                            class="w-full px-2 py-1.5 text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/30 rounded transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                                            :title="selectedProducts.length === 1 ? 'Debe haber al menos un producto' : 'Eliminar producto'"
                                        >
                                            <GoogleIcon name="delete" class="text-lg" />
                                        </button>
                                    </div>

                                    <!-- Selección de seriales (solo si el producto requiere seriales) -->
                                    <div v-if="item.inventory_id && item.track_serials" class="col-span-12">
                                        <!-- Advertencia si la unidad permite decimales -->
                                        <div v-if="!canUseSerials(item)" class="mt-2 p-2 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg">
                                            <div class="flex items-start gap-2">
                                                <GoogleIcon name="warning" class="text-red-600 dark:text-red-400 text-lg shrink-0 mt-0.5" />
                                                <div>
                                                    <p class="text-xs font-semibold text-red-900 dark:text-red-100">
                                                        No se pueden usar números de serie con esta unidad de medida
                                                    </p>
                                                    <p class="text-xs text-red-700 dark:text-red-300 mt-1">
                                                        Este producto usa la unidad <strong>{{ item.unit_of_measure?.name }} ({{ item.unit_of_measure?.abbreviation }})</strong> que permite cantidades decimales.
                                                    </p>
                                                </div>
                                            </div>
                                        </div>

                                        <div v-else class="mt-2 p-2 bg-amber-50 dark:bg-amber-900/10 border border-amber-200 dark:border-amber-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-amber-600 dark:text-amber-400 text-lg" />
                                                    <div>
                                                        <p class="text-xs font-semibold text-amber-900 dark:text-amber-100">
                                                            Este producto requiere números de serie
                                                        </p>
                                                        <p class="text-xs text-amber-700 dark:text-amber-300">
                                                            {{ item.selected_serials.length }} de {{ item.available_serials_count }} seriales seleccionados
                                                        </p>
                                                    </div>
                                                </div>
                                                <button
                                                    type="button"
                                                    @click="openSerialSelector(item, index)"
                                                    class="flex items-center gap-1 px-3 py-1.5 text-xs font-semibold text-white bg-amber-600 hover:bg-amber-700 rounded transition-colors"
                                                >
                                                    <GoogleIcon name="qr_code_scanner" class="text-sm" />
                                                    {{ item.selected_serials.length > 0 ? 'Cambiar' : 'Seleccionar' }}
                                                </button>
                                            </div>
                                            <!-- Lista de seriales seleccionados -->
                                            <div v-if="item.selected_serials.length > 0" class="mt-2 pt-2 border-t border-amber-200 dark:border-amber-800">
                                                <p class="text-xs font-medium text-amber-900 dark:text-amber-100 mb-1">Seriales seleccionados:</p>
                                                <div class="flex flex-wrap gap-1">
                                                    <span
                                                        v-for="(serial, sIndex) in item.selected_serials.slice(0, 5)"
                                                        :key="sIndex"
                                                        class="inline-flex items-center px-2 py-0.5 text-xs font-mono bg-amber-100 dark:bg-amber-900/30 text-amber-800 dark:text-amber-200 rounded"
                                                    >
                                                        {{ serial }}
                                                    </span>
                                                    <span
                                                        v-if="item.selected_serials.length > 5"
                                                        class="inline-flex items-center px-2 py-0.5 text-xs bg-amber-100 dark:bg-amber-900/30 text-amber-700 dark:text-amber-300 rounded"
                                                    >
                                                        +{{ item.selected_serials.length - 5 }} más
                                                    </span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <FormError :message="form.errors?.products" />
                    </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="Ej: Producto dañado"
                            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"
                        ></textarea>
                        <FormError :message="form.errors?.notes" />
                    </div>
                </div>

                <!-- Botones -->
                <div class="flex items-center justify-end gap-3 mt-6">
                    <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 || selectedProducts.length === 0"
                        class="flex items-center gap-2 px-4 py-2 text-sm font-semibold text-white bg-red-600 rounded-lg hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                    >
                        <GoogleIcon name="remove_circle" class="text-lg" />
                        <span v-if="form.processing">Registrando...</span>
                        <span v-else>Registrar Salida</span>
                    </button>
                </div>
            </form>
        </div>

        <!-- Modal de Selección de Seriales -->
        <SerialSelector
            v-if="currentProductForSerials && currentProductIndex !== null"
            :show="showSerialSelector"
            :product="currentProductForSerials"
            :warehouse-id="Number(form.warehouse_id)"
            :initial-serials="selectedProducts[currentProductIndex]?.selected_serials || []"
            @close="closeSerialSelector"
            @confirm="handleSerialsConfirmed"
        />
    </Modal>
</template>
