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

const props = defineProps({
    modelValue: {
        type: String,
        default: ''
    },
    excludeIds: {
        type: Array,
        default: () => []
    },
    placeholder: {
        type: String,
        default: 'Buscar producto por nombre o SKU...'
    },
    disabled: {
        type: Boolean,
        default: false
    }
});

const emit = defineEmits(['update:modelValue', 'select']);

const api = useApi();
const productSuggestions = ref([]);
const showSuggestions = ref(false);
const searchingProduct = ref(false);
const productNotFound = ref(false);
let debounceTimer = null;

const localValue = ref(props.modelValue);

watch(() => props.modelValue, (newVal) => {
    localValue.value = newVal;
});

watch(localValue, (newVal) => {
    emit('update:modelValue', newVal);
    onProductInput();
});

const onProductInput = () => {
    productNotFound.value = false;

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

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

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

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

    api.get(apiURL(`inventario?q=${encodeURIComponent(searchValue)}`), {
        onSuccess: (data) => {
            const foundProducts = data.products?.data || data.data || [];

            // Filtrar productos ya agregados
            const filteredProducts = foundProducts.filter(
                p => !props.excludeIds.includes(p.id)
            );

            if (filteredProducts.length > 0) {
                productSuggestions.value = filteredProducts;
                showSuggestions.value = true;
            } else {
                productSuggestions.value = [];
                showSuggestions.value = false;
                productNotFound.value = true;
            }
        },
        onFail: () => {
            productSuggestions.value = [];
            showSuggestions.value = false;
            productNotFound.value = true;
        },
        onError: () => {
            productSuggestions.value = [];
            showSuggestions.value = false;
            productNotFound.value = true;
        },
        onFinish: () => {
            searchingProduct.value = false;
        }
    });
};

const selectProduct = (product) => {
    emit('select', product);
    localValue.value = '';
    productSuggestions.value = [];
    showSuggestions.value = false;
    productNotFound.value = false;
};

const closeSuggestions = () => {
    setTimeout(() => {
        showSuggestions.value = false;
    }, 200);
};
</script>

<template>
    <div class="relative">
        <div class="relative">
            <input
                v-model="localValue"
                type="text"
                :placeholder="placeholder"
                :disabled="disabled"
                @blur="closeSuggestions"
                @keydown.enter.prevent="searchProduct"
                class="w-full px-3 py-2 pr-10 text-sm border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-800 dark:text-gray-100 disabled:opacity-50 disabled:cursor-not-allowed"
            />
            <div class="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
                <GoogleIcon
                    v-if="searchingProduct"
                    name="hourglass_empty"
                    class="text-gray-400 text-lg animate-spin"
                />
                <GoogleIcon
                    v-else
                    name="search"
                    class="text-gray-400 text-lg"
                />
            </div>
        </div>

        <!-- Sugerencias -->
        <div
            v-if="showSuggestions && productSuggestions.length > 0"
            class="absolute z-10 w-full mt-1 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg shadow-lg max-h-60 overflow-y-auto"
        >
            <button
                v-for="product in productSuggestions"
                :key="product.id"
                @click="selectProduct(product)"
                class="w-full px-4 py-3 text-left hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors border-b border-gray-200 dark:border-gray-700 last:border-b-0"
            >
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-semibold text-gray-900 dark:text-gray-100">
                            {{ product.name }}
                        </p>
                        <p class="text-xs text-gray-500 dark:text-gray-400">
                            SKU: {{ product.sku }} | Stock: {{ product.stock }}
                        </p>
                    </div>
                    <div class="text-right">
                        <p class="text-xs text-gray-500 dark:text-gray-400">Precio</p>
                        <p class="text-sm font-semibold text-gray-900 dark:text-gray-100">
                            {{ formatCurrency(product.price?.retail_price) }}
                        </p>
                    </div>
                </div>
            </button>
        </div>

        <!-- Mensaje de no encontrado -->
        <div
            v-if="productNotFound && !searchingProduct"
            class="absolute z-10 w-full mt-1 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg shadow-lg p-4"
        >
            <div class="flex items-center gap-2 text-gray-500 dark:text-gray-400">
                <GoogleIcon name="search_off" class="text-xl" />
                <p class="text-sm">No se encontraron productos</p>
            </div>
        </div>
    </div>
</template>
