<script setup>
import { ref, watch, computed } from 'vue';
import { MagnifyingGlassIcon, XMarkIcon } from '@heroicons/vue/24/outline';

const props = defineProps({
    modelValue: [String, Number],
    mealType: String,
    placeholder: String,
    error: String,
});

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

const foods = ref([]);
const loading = ref(false);
const searchQuery = ref('');
const showDropdown = ref(false);
const selectedFood = ref(null);

// Cargar alimentos cuando cambia el tipo de comida
watch(() => props.mealType, async (newMealType) => {
    if (newMealType) {
        await loadFoods(newMealType);
    }
}, { immediate: true });

// Cargar alimentos del servidor
const loadFoods = async (mealType) => {
    loading.value = true;
    try {
        const response = await fetch(`/api/foods?meal_type=${mealType}`);
        const data = await response.json();
        foods.value = data;
        
        // Si ya hay un valor seleccionado, encontrarlo
        if (props.modelValue) {
            selectedFood.value = foods.value.find(f => f.id === parseInt(props.modelValue));
        }
    } catch (error) {
    } finally {
        loading.value = false;
    }
};

// Filtrar alimentos por búsqueda
const filteredFoods = computed(() => {
    if (!searchQuery.value) {
        return foods.value;
    }
    
    const query = searchQuery.value.toLowerCase();
    return foods.value.filter(food => 
        food.name.toLowerCase().includes(query)
    );
});

// Seleccionar un alimento
const selectFood = (food) => {
    selectedFood.value = food;
    emit('update:modelValue', food.id);
    showDropdown.value = false;
    searchQuery.value = '';
};

// Limpiar selección
const clearSelection = () => {
    selectedFood.value = null;
    emit('update:modelValue', null);
    searchQuery.value = '';
};

// Abrir dropdown
const openDropdown = () => {
    showDropdown.value = true;
};

// Cerrar dropdown al hacer click fuera
const closeDropdown = () => {
    setTimeout(() => {
        showDropdown.value = false;
    }, 200);
};
</script>

<template>
    <div class="relative">
        <!-- Campo de selección/búsqueda -->
        <div class="relative">
            <div
                v-if="selectedFood"
                class="flex items-center justify-between w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
            >
                <div class="flex-1">
                    <div class="font-medium">{{ selectedFood.name }}</div>
                    <div v-if="selectedFood.serving_size" class="text-xs text-gray-500 dark:text-gray-400">
                        {{ selectedFood.serving_size }}
                        <span v-if="selectedFood.calories">• {{ selectedFood.calories }} kcal</span>
                    </div>
                </div>
                <button
                    @click="clearSelection"
                    type="button"
                    class="ml-2 p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
                >
                    <XMarkIcon class="h-5 w-5" />
                </button>
            </div>

            <div v-else class="relative">
                <input
                    v-model="searchQuery"
                    @focus="openDropdown"
                    @blur="closeDropdown"
                    type="text"
                    :placeholder="placeholder || 'Buscar alimento...'"
                    class="block w-full pl-10 pr-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-700 dark:text-gray-100"
                    :class="{ 'border-red-500': error }"
                />
                <MagnifyingGlassIcon class="absolute left-3 top-2.5 h-5 w-5 text-gray-400" />
            </div>
        </div>

        <!-- Mensaje de error -->
        <p v-if="error" class="mt-1 text-sm text-red-600 dark:text-red-400">
            {{ error }}
        </p>

        <!-- Dropdown de resultados -->
        <div
            v-if="showDropdown && !selectedFood"
            class="absolute z-10 mt-1 w-full bg-white dark:bg-gray-800 shadow-lg max-h-60 rounded-md py-1 text-base ring-1 ring-black ring-opacity-5 overflow-auto focus:outline-none sm:text-sm"
        >
            <!-- Loading state -->
            <div v-if="loading" class="px-4 py-3 text-center text-gray-500 dark:text-gray-400">
                Cargando alimentos...
            </div>

            <!-- Empty state -->
            <div v-else-if="filteredFoods.length === 0" class="px-4 py-3 text-center text-gray-500 dark:text-gray-400">
                {{ searchQuery ? 'No se encontraron alimentos' : 'No hay alimentos disponibles para este tipo de comida' }}
            </div>

            <!-- Lista de alimentos -->
            <button
                v-for="food in filteredFoods"
                :key="food.id"
                @click="selectFood(food)"
                type="button"
                class="w-full text-left px-4 py-2 hover:bg-gray-100 dark:hover:bg-gray-700 cursor-pointer"
            >
                <div class="font-medium text-gray-900 dark:text-gray-100">
                    {{ food.name }}
                </div>
                <div v-if="food.serving_size || food.calories" class="text-xs text-gray-500 dark:text-gray-400">
                    <span v-if="food.serving_size">{{ food.serving_size }}</span>
                    <span v-if="food.serving_size && food.calories"> • </span>
                    <span v-if="food.calories">{{ food.calories }} kcal</span>
                    <span v-if="food.proteins || food.carbs || food.fats"> • P: {{ food.proteins }}g C: {{ food.carbs }}g G: {{ food.fats }}g</span>
                </div>
            </button>
        </div>
    </div>
</template>
