<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({
    exercises: Object,
    filters: Object,
    categories: [Array, Object],
    muscleGroups: [Array, Object],
});

const search = ref(props.filters.search || '');
const category = ref(props.filters.category || '');
const muscleGroup = ref(props.filters.muscle_group || '');
const selectedExercise = ref(null);

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

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

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

const showExerciseDetail = (exercise) => {
    selectedExercise.value = exercise;
};

const deleteExercise = (exercise) => {
    if (!exercise.coach_id) {
        alert('No puedes eliminar ejercicios del sistema');
        return;
    }
    if (confirm(`¿Eliminar el ejercicio "${exercise.name}"?`)) {
        router.delete(route('coach.exercises.destroy', exercise.id));
    }
};
</script>

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

    <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 Ejercicios
                    </h2>
                    <p class="text-sm text-gray-500 dark:text-gray-400 mt-1">
                        Gestiona tu catálogo de ejercicios
                    </p>
                </div>
                <Link 
                    :href="route('coach.exercises.create')"
                    class="hidden lg:inline-flex items-center px-4 py-2 bg-gradient-to-r from-orange-500 to-red-500 hover:from-orange-600 hover:to-red-600 text-white font-medium rounded-lg shadow-lg shadow-orange-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 Ejercicio
                </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 ejercicios..."
                            class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white focus:ring-orange-500 focus:border-orange-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-orange-500 focus:border-orange-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="muscleGroup"
                            class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white focus:ring-orange-500 focus:border-orange-500"
                        >
                            <option value="">Todos los grupos</option>
                            <option v-for="mg in muscleGroups" :key="mg" :value="mg">{{ mg }}</option>
                        </select>
                    </div>
                </div>
                <div v-if="search || category || muscleGroup" class="mt-3">
                    <button @click="clearFilters" class="text-sm text-orange-600 dark:text-orange-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 ejercicios..."
                        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-orange-500 focus:border-transparent text-base touch-manipulation"
                    />
                </div>
                <!-- Active filter chips -->
                <div v-if="category || muscleGroup" 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-orange-100 dark:bg-orange-900/40 text-orange-700 dark:text-orange-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="muscleGroup" 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">
                        {{ muscleGroup }}
                        <button @click="muscleGroup = ''; 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>

            <!-- Exercises Grid -->
            <div v-if="exercises.data.length" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                <div 
                    v-for="exercise in exercises.data" 
                    :key="exercise.id"
                    class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-100 dark:border-gray-700 overflow-hidden hover:shadow-md transition-shadow group"
                >
                    <!-- GIF Preview -->
                    <div v-if="exercise.gif_url" class="aspect-video bg-gray-100 dark:bg-gray-700 overflow-hidden">
                        <img 
                            :src="exercise.gif_url" 
                            :alt="exercise.name"
                            class="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
                            loading="lazy"
                        />
                    </div>
                    <div v-else class="aspect-video bg-gradient-to-br from-gray-100 to-gray-200 dark:from-gray-700 dark:to-gray-800 flex items-center justify-center">
                        <span class="text-4xl">🏋️</span>
                    </div>
                    
                    <div class="p-4">
                        <div class="flex items-start justify-between">
                            <div class="flex-1">
                                <h3 class="font-semibold text-gray-900 dark:text-white line-clamp-1">{{ exercise.name }}</h3>
                                <div class="flex flex-wrap gap-1 mt-2">
                                    <span v-if="exercise.category" class="px-2 py-0.5 bg-orange-100 dark:bg-orange-900/50 text-orange-700 dark:text-orange-400 text-xs rounded-full">
                                        {{ exercise.category }}
                                    </span>
                                    <span v-if="exercise.muscle_group" 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">
                                        {{ exercise.muscle_group }}
                                    </span>
                                    <span v-if="exercise.difficulty" :class="[
                                        'px-2 py-0.5 text-xs rounded-full',
                                        exercise.difficulty === 'principiante' ? 'bg-green-100 dark:bg-green-900/50 text-green-700 dark:text-green-400' :
                                        exercise.difficulty === 'intermedio' ? 'bg-yellow-100 dark:bg-yellow-900/50 text-yellow-700 dark:text-yellow-400' :
                                        'bg-red-100 dark:bg-red-900/50 text-red-700 dark:text-red-400'
                                    ]">
                                        {{ exercise.difficulty }}
                                    </span>
                                </div>
                            </div>
                            <span v-if="exercise.is_system || !exercise.coach_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 ml-2">
                                ✓ Sistema
                            </span>
                        </div>
                        
                        <p v-if="exercise.description" class="text-sm text-gray-500 dark:text-gray-400 mt-2 line-clamp-2">
                            {{ exercise.description }}
                        </p>
                        
                        <div v-if="exercise.equipment" class="mt-3 flex items-center text-xs text-gray-500 dark:text-gray-400">
                            <span class="mr-1">🏋️</span>
                            {{ exercise.equipment }}
                        </div>
                    </div>
                    
                    <div class="px-4 py-3 border-t border-gray-100 dark:border-gray-700 flex justify-between items-center">
                        <button 
                            @click="showExerciseDetail(exercise)"
                            class="text-sm text-blue-600 dark:text-blue-400 hover:underline"
                        >
                            Ver detalle
                        </button>
                        <div class="flex gap-2">
                            <Link 
                                v-if="exercise.coach_id"
                                :href="route('coach.exercises.edit', exercise.id)"
                                class="px-3 py-1.5 text-sm text-gray-600 dark:text-gray-400 hover:text-orange-600 dark:hover:text-orange-400 transition-colors"
                            >
                                ✏️ Editar
                            </Link>
                            <button 
                                v-if="exercise.coach_id"
                                @click="deleteExercise(exercise)"
                                class="px-3 py-1.5 text-sm text-red-600 dark:text-red-400 hover:text-red-700 dark:hover:text-red-300 transition-colors"
                            >
                                🗑️
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Exercise Detail Modal -->
            <Teleport to="body">
                <div v-if="selectedExercise" class="fixed inset-0 z-50 flex items-end sm:items-center justify-center p-4" @click.self="selectedExercise = null">
                    <div class="fixed inset-0 bg-black/50 backdrop-blur-sm" @click="selectedExercise = null"></div>
                    <div class="relative bg-white dark:bg-gray-800 rounded-t-2xl sm:rounded-2xl shadow-xl w-full max-w-lg max-h-[90vh] overflow-hidden">
                        <!-- GIF -->
                        <div v-if="selectedExercise.gif_url" class="aspect-video bg-gray-100 dark:bg-gray-700">
                            <img :src="selectedExercise.gif_url" :alt="selectedExercise.name" class="w-full h-full object-contain" />
                        </div>
                        
                        <div class="p-6 overflow-y-auto max-h-[60vh]">
                            <div class="flex justify-between items-start mb-4">
                                <h3 class="text-xl font-bold text-gray-900 dark:text-white">{{ selectedExercise.name }}</h3>
                                <button @click="selectedExercise = null" class="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300">
                                    ✕
                                </button>
                            </div>
                            
                            <!-- Tags -->
                            <div class="flex flex-wrap gap-2 mb-4">
                                <span v-if="selectedExercise.category" class="px-3 py-1 bg-orange-100 dark:bg-orange-900/50 text-orange-700 dark:text-orange-400 text-sm rounded-full">
                                    {{ selectedExercise.category }}
                                </span>
                                <span v-if="selectedExercise.muscle_group" class="px-3 py-1 bg-blue-100 dark:bg-blue-900/50 text-blue-700 dark:text-blue-400 text-sm rounded-full">
                                    {{ selectedExercise.muscle_group }}
                                </span>
                                <span v-if="selectedExercise.equipment" class="px-3 py-1 bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 text-sm rounded-full">
                                    🏋️ {{ selectedExercise.equipment }}
                                </span>
                            </div>
                            
                            <!-- Description -->
                            <p v-if="selectedExercise.description" class="text-gray-600 dark:text-gray-400 mb-4">
                                {{ selectedExercise.description }}
                            </p>
                            
                            <!-- Instructions -->
                            <div v-if="selectedExercise.instructions" class="mb-4">
                                <h4 class="font-semibold text-gray-900 dark:text-white mb-2">📋 Instrucciones</h4>
                                <div class="bg-gray-50 dark:bg-gray-700/50 rounded-lg p-4 text-sm text-gray-700 dark:text-gray-300 whitespace-pre-line">
                                    {{ selectedExercise.instructions }}
                                </div>
                            </div>
                            
                            <!-- Video -->
                            <a v-if="selectedExercise.video_url" :href="selectedExercise.video_url" target="_blank" class="inline-flex items-center gap-2 text-blue-600 dark:text-blue-400 hover:underline">
                                🎬 Ver video tutorial
                            </a>
                        </div>
                    </div>
                </div>
            </Teleport>

            <!-- Empty State -->
            <div v-if="!exercises.data.length" 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="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
                    </svg>
                </div>
                <h3 class="text-xl font-semibold text-gray-900 dark:text-white mb-2">No se encontraron ejercicios</h3>
                <p class="text-gray-500 dark:text-gray-400 mb-6">
                    {{ (search || category || muscleGroup) ? 'Prueba con otros filtros' : 'Crea tu primer ejercicio personalizado' }}
                </p>
                <Link 
                    :href="route('coach.exercises.create')"
                    class="inline-flex items-center px-4 py-2 bg-orange-600 hover:bg-orange-700 text-white font-medium rounded-lg transition-colors"
                >
                    Crear ejercicio →
                </Link>
            </div>

            <!-- Pagination -->
            <div v-if="exercises.links?.length > 3" class="flex justify-center gap-1">
                <Link 
                    v-for="link in exercises.links" 
                    :key="link.label"
                    :href="link.url"
                    :class="[
                        'px-4 py-2 rounded-lg text-sm transition-colors',
                        link.active 
                            ? 'bg-orange-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 Ejercicio"
            color="indigo"
            :extended="true"
            @click="$inertia.visit(route('coach.exercises.create'))"
        />

        <!-- Mobile Filter BottomSheet -->
        <BottomSheet v-model="showFilterSheet" title="Filtrar ejercicios" :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-orange-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-orange-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">Grupo muscular</label>
                    <div class="grid grid-cols-2 gap-2">
                        <button
                            @click="muscleGroup = ''"
                            :class="['py-3 rounded-xl text-sm font-medium transition-all touch-manipulation', muscleGroup === '' ? '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="mg in muscleGroups" :key="mg"
                            @click="muscleGroup = mg"
                            :class="['py-3 rounded-xl text-sm font-medium transition-all touch-manipulation truncate', muscleGroup === mg ? 'bg-blue-600 text-white shadow-md' : 'bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300']"
                        >{{ mg }}</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-orange-600 hover:bg-orange-700 text-white rounded-xl font-medium touch-manipulation">Aplicar</button>
                </div>
            </template>
        </BottomSheet>
    </CoachLayout>
</template>
