<script setup>
import CoachLayout from '@/Layouts/CoachLayout.vue';
import { Head, Link, router } from '@inertiajs/vue3';
import { ref, watch } from 'vue';
import debounce from 'lodash/debounce';
import FloatingActionButton from '@/Components/Mobile/FloatingActionButton.vue';
import PullToRefresh from '@/Components/Mobile/PullToRefresh.vue';
import BottomSheet from '@/Components/Mobile/BottomSheet.vue';

const isRefreshing = ref(false);
const showFilterSheet = ref(false);
const handleRefresh = () => {
    isRefreshing.value = true;
    router.reload({ onFinish: () => { isRefreshing.value = false; } });
};

const props = defineProps({
    foods: Object,
    filters: Object,
    categories: Array,
    mealTypes: Object,
});

const search = ref(props.filters.search || '');
const category = ref(props.filters.category || '');
const mealType = ref(props.filters.meal_type || '');

const applyFilters = debounce(() => {
    router.get(route('coach.foods.index'), {
        search: search.value,
        category: category.value,
        meal_type: mealType.value,
    }, { preserveState: true });
}, 300);

watch([search, category, mealType], () => {
    applyFilters();
});

const clearFilters = () => {
    search.value = '';
    category.value = '';
    mealType.value = '';
    showFilterSheet.value = false;
    applyFilters();
};

const deleteFood = (food) => {
    if (!food.user_id) {
        alert('No puedes eliminar alimentos del sistema');
        return;
    }
    if (confirm(`¿Eliminar el alimento "${food.name}"?`)) {
        router.delete(route('coach.foods.destroy', food.id));
    }
};

const getMealTypeLabel = (type) => {
    return props.mealTypes?.[type] || type || '-';
};
</script>

<template>
    <Head title="Biblioteca de Alimentos" />

    <CoachLayout>
        <template #header>
            <div class="flex flex-col sm:flex-row sm:justify-between sm:items-center gap-4">
                <div>
                    <h2 class="text-xl font-bold text-gray-900 dark:text-white">
                        Biblioteca de Alimentos
                    </h2>
                    <p class="text-sm text-gray-500 dark:text-gray-400 mt-1">
                        Gestiona tu catálogo de alimentos
                    </p>
                </div>
                <Link 
                    :href="route('coach.foods.create')"
                    class="hidden lg:inline-flex items-center px-4 py-2 bg-gradient-to-r from-green-500 to-emerald-500 hover:from-green-600 hover:to-emerald-600 text-white font-medium rounded-lg shadow-lg shadow-green-500/25 transition-all"
                >
                    <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
                    </svg>
                    Nuevo Alimento
                </Link>
                <!-- Mobile: filter button -->
                <button
                    @click="showFilterSheet = true"
                    class="lg:hidden inline-flex items-center px-3 py-2 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors touch-manipulation"
                >
                    <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="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z" />
                    </svg>
                </button>
            </div>
        </template>

        <PullToRefresh :loading="isRefreshing" @refresh="handleRefresh">
        <div class="space-y-6">
            <!-- Desktop Filters -->
            <div class="hidden lg:block bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-100 dark:border-gray-700 p-4">
                <div class="grid grid-cols-4 gap-4">
                    <div class="col-span-2">
                        <input 
                            v-model="search"
                            type="text" 
                            placeholder="Buscar alimentos..."
                            class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white focus:ring-green-500 focus:border-green-500"
                        />
                    </div>
                    <div>
                        <select 
                            v-model="category"
                            class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white focus:ring-green-500 focus:border-green-500"
                        >
                            <option value="">Todas las categorías</option>
                            <option v-for="cat in categories" :key="cat" :value="cat">{{ cat }}</option>
                        </select>
                    </div>
                    <div>
                        <select 
                            v-model="mealType"
                            class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white focus:ring-green-500 focus:border-green-500"
                        >
                            <option value="">Todos los tipos</option>
                            <option v-for="(label, key) in mealTypes" :key="key" :value="key">{{ label }}</option>
                        </select>
                    </div>
                </div>
                <div v-if="search || category || mealType" class="mt-3">
                    <button @click="clearFilters" class="text-sm text-green-600 dark:text-green-400 hover:underline">
                        Limpiar filtros
                    </button>
                </div>
            </div>

            <!-- Mobile: Search bar -->
            <div class="lg:hidden">
                <div class="relative">
                    <svg class="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                    </svg>
                    <input
                        v-model="search"
                        type="text"
                        placeholder="Buscar alimentos..."
                        class="w-full pl-10 pr-4 py-3 rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500 focus:ring-2 focus:ring-green-500 focus:border-transparent text-base touch-manipulation"
                    />
                </div>
                <!-- Active filter chips -->
                <div v-if="category || mealType" class="flex flex-wrap items-center gap-2 mt-2">
                    <span v-if="category" class="inline-flex items-center gap-1 px-3 py-1 bg-green-100 dark:bg-green-900/40 text-green-700 dark:text-green-300 rounded-full text-xs font-medium">
                        {{ category }}
                        <button @click="category = ''; applyFilters()" class="ml-0.5">
                            <svg class="w-3 h-3" 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>
                    </span>
                    <span v-if="mealType" class="inline-flex items-center gap-1 px-3 py-1 bg-blue-100 dark:bg-blue-900/40 text-blue-700 dark:text-blue-300 rounded-full text-xs font-medium">
                        {{ getMealTypeLabel(mealType) }}
                        <button @click="mealType = ''; applyFilters()" class="ml-0.5">
                            <svg class="w-3 h-3" 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>
                    </span>
                </div>
            </div>

            <!-- Foods Table (Desktop only) -->
            <div v-if="foods.data.length" class="hidden lg:block bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-100 dark:border-gray-700 overflow-hidden">
                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead class="bg-gray-50 dark:bg-gray-700/50">
                            <tr>
                                <th class="px-6 py-3 text-left text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">Alimento</th>
                                <th class="px-6 py-3 text-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">Porción</th>
                                <th class="px-6 py-3 text-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">Calorías</th>
                                <th class="px-6 py-3 text-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">Proteína</th>
                                <th class="px-6 py-3 text-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">Carbos</th>
                                <th class="px-6 py-3 text-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">Grasas</th>
                                <th class="px-6 py-3 text-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">Fibra</th>
                                <th class="px-6 py-3 text-right text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">Acciones</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-200 dark:divide-gray-700">
                            <tr v-for="food in foods.data" :key="food.id" class="hover:bg-gray-50 dark:hover:bg-gray-700/50">
                                <td class="px-6 py-4">
                                    <div>
                                        <p class="font-medium text-gray-900 dark:text-white">{{ food.name }}</p>
                                        <div class="flex flex-wrap items-center gap-2 mt-1">
                                            <span v-if="food.category" class="px-2 py-0.5 bg-green-100 dark:bg-green-900/50 text-green-700 dark:text-green-400 text-xs rounded-full">
                                                {{ food.category }}
                                            </span>
                                            <span v-if="food.meal_type" class="px-2 py-0.5 bg-blue-100 dark:bg-blue-900/50 text-blue-700 dark:text-blue-400 text-xs rounded-full">
                                                {{ getMealTypeLabel(food.meal_type) }}
                                            </span>
                                            <span v-if="!food.user_id" class="px-2 py-0.5 bg-gray-100 dark:bg-gray-700 text-gray-500 dark:text-gray-400 text-xs rounded-full">
                                                Sistema
                                            </span>
                                        </div>
                                    </div>
                                </td>
                                <td class="px-6 py-4 text-center text-gray-500 dark:text-gray-400">
                                    <div v-if="food.serving_size">
                                        <div class="text-sm">{{ food.serving_size }}</div>
                                        <div v-if="food.serving_weight" class="text-xs text-gray-400">{{ food.serving_weight }}g</div>
                                    </div>
                                    <span v-else>100g</span>
                                </td>
                                <td class="px-6 py-4 text-center">
                                    <span class="font-semibold text-gray-900 dark:text-white">{{ food.calories }}</span>
                                    <span class="text-gray-400 text-sm">kcal</span>
                                </td>
                                <td class="px-6 py-4 text-center text-blue-600 dark:text-blue-400 font-medium">{{ food.proteins }}g</td>
                                <td class="px-6 py-4 text-center text-yellow-600 dark:text-yellow-400 font-medium">{{ food.carbs }}g</td>
                                <td class="px-6 py-4 text-center text-orange-600 dark:text-orange-400 font-medium">{{ food.fats }}g</td>
                                <td class="px-6 py-4 text-center text-green-600 dark:text-green-400">{{ food.fiber || 0 }}g</td>
                                <td class="px-6 py-4 text-right">
                                    <div class="flex justify-end gap-2">
                                        <template v-if="food.user_id">
                                            <Link 
                                                :href="route('coach.foods.edit', food.id)"
                                                class="text-sm text-green-600 dark:text-green-400 hover:text-green-700 dark:hover:text-green-300 transition-colors"
                                            >
                                                Editar
                                            </Link>
                                            <button 
                                                @click="deleteFood(food)"
                                                class="text-sm text-red-600 dark:text-red-400 hover:text-red-700 dark:hover:text-red-300 transition-colors"
                                            >
                                                Eliminar
                                            </button>
                                        </template>
                                        <template v-else>
                                            <Link 
                                                :href="route('coach.foods.create', { copy: food.id })"
                                                class="text-sm text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 transition-colors"
                                                title="Copiar este alimento para personalizarlo"
                                            >
                                                Copiar
                                            </Link>
                                            <span class="text-xs text-gray-400 dark:text-gray-500" title="Alimento del sistema">
                                                Sistema
                                            </span>
                                        </template>
                                    </div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- Foods Cards (Mobile only) -->
            <div v-if="foods.data.length" class="lg:hidden grid grid-cols-1 gap-3">
                <div
                    v-for="food in foods.data"
                    :key="'m-' + food.id"
                    class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-100 dark:border-gray-700 p-4 touch-manipulation active:scale-[0.98] transition-transform"
                >
                    <div class="flex items-start justify-between mb-3">
                        <div class="flex-1 min-w-0">
                            <h3 class="font-semibold text-gray-900 dark:text-white truncate">{{ food.name }}</h3>
                            <div class="flex flex-wrap gap-1 mt-1">
                                <span v-if="food.category" class="px-2 py-0.5 bg-green-100 dark:bg-green-900/50 text-green-700 dark:text-green-400 text-xs rounded-full">
                                    {{ food.category }}
                                </span>
                                <span v-if="food.meal_type" class="px-2 py-0.5 bg-blue-100 dark:bg-blue-900/50 text-blue-700 dark:text-blue-400 text-xs rounded-full">
                                    {{ getMealTypeLabel(food.meal_type) }}
                                </span>
                                <span v-if="!food.user_id" class="px-2 py-0.5 bg-gray-100 dark:bg-gray-700 text-gray-500 dark:text-gray-400 text-xs rounded-full">
                                    Sistema
                                </span>
                            </div>
                        </div>
                        <div class="text-right ml-3">
                            <div class="text-xl font-bold text-gray-900 dark:text-white">{{ food.calories }}</div>
                            <div class="text-xs text-gray-400">kcal</div>
                        </div>
                    </div>
                    <!-- Macro row -->
                    <div class="grid grid-cols-4 gap-2 py-2 border-t border-gray-100 dark:border-gray-700">
                        <div class="text-center">
                            <div class="text-sm font-semibold text-blue-600 dark:text-blue-400">{{ food.proteins }}g</div>
                            <div class="text-[10px] text-gray-400 uppercase">Prot</div>
                        </div>
                        <div class="text-center">
                            <div class="text-sm font-semibold text-yellow-600 dark:text-yellow-400">{{ food.carbs }}g</div>
                            <div class="text-[10px] text-gray-400 uppercase">Carbs</div>
                        </div>
                        <div class="text-center">
                            <div class="text-sm font-semibold text-orange-600 dark:text-orange-400">{{ food.fats }}g</div>
                            <div class="text-[10px] text-gray-400 uppercase">Grasas</div>
                        </div>
                        <div class="text-center">
                            <div class="text-sm font-semibold text-green-600 dark:text-green-400">{{ food.fiber || 0 }}g</div>
                            <div class="text-[10px] text-gray-400 uppercase">Fibra</div>
                        </div>
                    </div>
                    <!-- Actions -->
                    <div class="flex justify-end gap-3 pt-2 border-t border-gray-100 dark:border-gray-700">
                        <template v-if="food.user_id">
                            <Link 
                                :href="route('coach.foods.edit', food.id)"
                                class="px-3 py-2 text-sm text-green-600 dark:text-green-400 font-medium touch-manipulation"
                            >
                                Editar
                            </Link>
                            <button 
                                @click="deleteFood(food)"
                                class="px-3 py-2 text-sm text-red-600 dark:text-red-400 font-medium touch-manipulation"
                            >
                                Eliminar
                            </button>
                        </template>
                        <template v-else>
                            <Link 
                                :href="route('coach.foods.create', { copy: food.id })"
                                class="px-3 py-2 text-sm text-blue-600 dark:text-blue-400 font-medium touch-manipulation"
                            >
                                Copiar
                            </Link>
                        </template>
                    </div>
                </div>
            </div>

            <!-- Empty State -->
            <div v-else class="text-center py-16 bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-100 dark:border-gray-700">
                <div class="w-20 h-20 bg-gray-100 dark:bg-gray-700 rounded-full flex items-center justify-center mx-auto mb-4">
                    <svg class="w-10 h-10 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253" />
                    </svg>
                </div>
                <h3 class="text-xl font-semibold text-gray-900 dark:text-white mb-2">No se encontraron alimentos</h3>
                <p class="text-gray-500 dark:text-gray-400 mb-6">
                    {{ (search || category) ? 'Prueba con otros filtros' : 'Crea tu primer alimento personalizado' }}
                </p>
                <Link 
                    :href="route('coach.foods.create')"
                    class="inline-flex items-center px-4 py-2 bg-green-600 hover:bg-green-700 text-white font-medium rounded-lg transition-colors"
                >
                    Crear alimento →
                </Link>
            </div>

            <!-- Pagination -->
            <div v-if="foods.links?.length > 3" class="flex justify-center gap-1">
                <Link 
                    v-for="link in foods.links" 
                    :key="link.label"
                    :href="link.url"
                    :class="[
                        'px-4 py-2 rounded-lg text-sm transition-colors',
                        link.active 
                            ? 'bg-green-600 text-white' 
                            : 'bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 border border-gray-200 dark:border-gray-600'
                    ]"
                    v-html="link.label"
                />
            </div>
        </div>
        </PullToRefresh>

        <!-- Mobile FAB -->
        <FloatingActionButton
            class="lg:hidden"
            icon="plus"
            label="Nuevo Alimento"
            color="green"
            :extended="true"
            @click="$inertia.visit(route('coach.foods.create'))"
        />

        <!-- Mobile Filter BottomSheet -->
        <BottomSheet v-model="showFilterSheet" title="Filtrar alimentos" :snap-points="[0.5]">
            <div class="space-y-5">
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Categoría</label>
                    <div class="grid grid-cols-2 gap-2">
                        <button
                            @click="category = ''"
                            :class="['py-3 rounded-xl text-sm font-medium transition-all touch-manipulation', category === '' ? 'bg-green-600 text-white shadow-md' : 'bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300']"
                        >Todas</button>
                        <button
                            v-for="cat in categories" :key="cat"
                            @click="category = cat"
                            :class="['py-3 rounded-xl text-sm font-medium transition-all touch-manipulation truncate', category === cat ? 'bg-green-600 text-white shadow-md' : 'bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300']"
                        >{{ cat }}</button>
                    </div>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Tipo de comida</label>
                    <div class="grid grid-cols-2 gap-2">
                        <button
                            @click="mealType = ''"
                            :class="['py-3 rounded-xl text-sm font-medium transition-all touch-manipulation', mealType === '' ? 'bg-blue-600 text-white shadow-md' : 'bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300']"
                        >Todos</button>
                        <button
                            v-for="(label, key) in mealTypes" :key="key"
                            @click="mealType = key"
                            :class="['py-3 rounded-xl text-sm font-medium transition-all touch-manipulation truncate', mealType === key ? 'bg-blue-600 text-white shadow-md' : 'bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300']"
                        >{{ label }}</button>
                    </div>
                </div>
            </div>
            <template #footer>
                <div class="flex gap-3">
                    <button @click="clearFilters" class="flex-1 py-3 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-xl font-medium touch-manipulation">Limpiar</button>
                    <button @click="showFilterSheet = false" class="flex-1 py-3 bg-green-600 hover:bg-green-700 text-white rounded-xl font-medium touch-manipulation">Aplicar</button>
                </div>
            </template>
        </BottomSheet>
    </CoachLayout>
</template>
