<script setup>
/**
 * Coach Create Workout Template with Blocks System
 * Supports exercise library with GIFs and muscle group filtering
 */
import CoachLayout from '@/Layouts/CoachLayout.vue';
import { Head, Link, useForm, router } from '@inertiajs/vue3';
import { ref, computed, watch } from 'vue';

const props = defineProps({
    exercises: Array,
    muscleGroups: Object,
    categories: Object,
});

const form = useForm({
    name: '',
    description: '',
    type: '',
    days: [
        { 
            name: 'Día 1', 
            blocks: [
                { name: 'Bloque Principal', exercises: [] }
            ] 
        }
    ],
});

const activeDayIndex = ref(0);
const activeBlockIndex = ref(0);
const showExerciseLibrary = ref(false);
const selectedMuscleGroup = ref('');
const selectedCategory = ref('');
const exerciseSearch = ref('');
const targetBlockForExercise = ref({ day: 0, block: 0 });

// Muscle group icons
const muscleIcons = {
    pecho: '💪',
    espalda: '🔙',
    hombros: '🎯',
    biceps: '💪',
    triceps: '💪',
    antebrazos: '🤜',
    abdominales: '🔥',
    oblicuos: '🔥',
    cuadriceps: '🦵',
    isquiotibiales: '🦵',
    gluteos: '🍑',
    pantorrillas: '🦶',
    aductores: '🦵',
    trapecio: '🔙',
    cuerpo_completo: '🏃',
};

// Filtered exercises
const filteredExercises = computed(() => {
    if (!props.exercises) return [];
    
    return props.exercises.filter(ex => {
        const matchesSearch = !exerciseSearch.value || 
            ex.name.toLowerCase().includes(exerciseSearch.value.toLowerCase());
        const matchesMuscle = !selectedMuscleGroup.value || 
            ex.muscle_group === selectedMuscleGroup.value;
        const matchesCategory = !selectedCategory.value || 
            ex.category === selectedCategory.value;
        return matchesSearch && matchesMuscle && matchesCategory;
    });
});

// Day management
const addDay = () => {
    form.days.push({ 
        name: `Día ${form.days.length + 1}`, 
        blocks: [{ name: 'Bloque Principal', exercises: [] }]
    });
    activeDayIndex.value = form.days.length - 1;
    activeBlockIndex.value = 0;
};

const removeDay = (index) => {
    if (form.days.length > 1) {
        form.days.splice(index, 1);
        if (activeDayIndex.value >= form.days.length) {
            activeDayIndex.value = form.days.length - 1;
        }
    }
};

// Block management
const addBlock = (dayIndex) => {
    const blocks = form.days[dayIndex].blocks;
    blocks.push({ 
        name: `Bloque ${blocks.length + 1}`, 
        exercises: [] 
    });
    activeBlockIndex.value = blocks.length - 1;
};

const removeBlock = (dayIndex, blockIndex) => {
    if (form.days[dayIndex].blocks.length > 1) {
        form.days[dayIndex].blocks.splice(blockIndex, 1);
        if (activeBlockIndex.value >= form.days[dayIndex].blocks.length) {
            activeBlockIndex.value = form.days[dayIndex].blocks.length - 1;
        }
    }
};

// Exercise management
const openExerciseLibrary = (dayIndex, blockIndex) => {
    targetBlockForExercise.value = { day: dayIndex, block: blockIndex };
    showExerciseLibrary.value = true;
    exerciseSearch.value = '';
    selectedMuscleGroup.value = '';
    selectedCategory.value = '';
};

const addExerciseFromLibrary = (exercise) => {
    const { day, block } = targetBlockForExercise.value;
    form.days[day].blocks[block].exercises.push({
        exercise_id: exercise.id,
        name: exercise.name,
        muscle_group: exercise.muscle_group,
        gif_url: exercise.gif_url,
        sets: 3,
        reps: '10-12',
        rest: '60',
        notes: '',
    });
    showExerciseLibrary.value = false;
};

const addCustomExercise = (dayIndex, blockIndex) => {
    form.days[dayIndex].blocks[blockIndex].exercises.push({
        exercise_id: null,
        name: '',
        muscle_group: '',
        gif_url: '',
        sets: 3,
        reps: '10-12',
        rest: '60',
        notes: '',
    });
};

const removeExercise = (dayIndex, blockIndex, exerciseIndex) => {
    form.days[dayIndex].blocks[blockIndex].exercises.splice(exerciseIndex, 1);
};

const moveExercise = (dayIndex, blockIndex, exerciseIndex, direction) => {
    const exercises = form.days[dayIndex].blocks[blockIndex].exercises;
    const newIndex = exerciseIndex + direction;
    if (newIndex >= 0 && newIndex < exercises.length) {
        [exercises[exerciseIndex], exercises[newIndex]] = [exercises[newIndex], exercises[exerciseIndex]];
    }
};

// Quick filter by muscle group
const filterByMuscle = (muscleKey) => {
    selectedMuscleGroup.value = muscleKey;
};

const getExerciseName = (id) => {
    if (!props.exercises) return '';
    const ex = props.exercises.find(e => e.id === parseInt(id));
    return ex ? ex.name : '';
};

const submit = () => {
    // Transform blocks to the expected format for backend
    const transformedDays = form.days.map(day => ({
        name: day.name,
        exercises: day.blocks.flatMap(block => 
            block.exercises.map((ex, idx) => ({
                ...ex,
                block_name: block.name,
                order: idx,
            }))
        ),
    }));
    
    form.transform(data => ({
        ...data,
        days: transformedDays,
    })).post(route('coach.workouts.store'));
};
</script>

<template>
    <Head title="Nueva Plantilla de Rutina" />

    <CoachLayout>
        <template #header>
            <div class="flex items-center gap-4">
                <Link 
                    :href="route('coach.workouts.index')"
                    class="p-2 text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
                >
                    <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="M10 19l-7-7m0 0l7-7m-7 7h18" />
                    </svg>
                </Link>
                <div>
                    <h2 class="text-xl font-bold text-gray-900 dark:text-white">
                        🏋️ Nueva Plantilla de Rutina
                    </h2>
                    <p class="text-sm text-gray-500 dark:text-gray-400">
                        Crea una rutina reutilizable con bloques de ejercicios
                    </p>
                </div>
            </div>
        </template>

        <form @submit.prevent="submit" class="space-y-6">
            <!-- Basic Info -->
            <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-100 dark:border-gray-700 p-6">
                <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4 flex items-center gap-2">
                    📝 Información General
                </h3>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div class="md:col-span-2">
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Nombre de la plantilla *</label>
                        <input 
                            v-model="form.name"
                            type="text"
                            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"
                            placeholder="Ej: Rutina de Fuerza - Principiantes"
                            required
                        />
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Tipo</label>
                        <select 
                            v-model="form.type"
                            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="">Seleccionar tipo</option>
                            <option value="strength">💪 Fuerza</option>
                            <option value="cardio">🏃 Cardio</option>
                            <option value="hiit">🔥 HIIT</option>
                            <option value="flexibility">🧘 Flexibilidad</option>
                            <option value="fullbody">🏋️ Full Body</option>
                            <option value="upper">⬆️ Tren Superior</option>
                            <option value="lower">⬇️ Tren Inferior</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Descripción</label>
                        <input 
                            v-model="form.description"
                            type="text"
                            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"
                            placeholder="Descripción breve de la rutina"
                        />
                    </div>
                </div>
            </div>

            <!-- Days Tabs -->
            <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-100 dark:border-gray-700">
                <div class="border-b border-gray-200 dark:border-gray-700 p-4">
                    <div class="flex items-center gap-2 flex-wrap">
                        <button
                            v-for="(day, index) in form.days"
                            :key="index"
                            type="button"
                            @click="activeDayIndex = index; activeBlockIndex = 0"
                            class="px-4 py-2 rounded-lg font-medium transition-colors relative group"
                            :class="{
                                'bg-orange-500 text-white shadow-lg shadow-orange-500/25': activeDayIndex === index,
                                'bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600': activeDayIndex !== index,
                            }"
                        >
                            📅 {{ day.name }}
                            <button
                                v-if="form.days.length > 1"
                                type="button"
                                @click.stop="removeDay(index)"
                                class="absolute -top-1 -right-1 w-5 h-5 bg-red-500 text-white rounded-full text-xs hidden group-hover:flex items-center justify-center"
                            >
                                ×
                            </button>
                        </button>
                        <button
                            type="button"
                            @click="addDay"
                            class="px-3 py-2 text-orange-600 dark:text-orange-400 hover:bg-orange-50 dark:hover:bg-orange-900/20 rounded-lg transition-colors"
                        >
                            <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="M12 4v16m8-8H4" />
                            </svg>
                        </button>
                    </div>
                </div>

                <!-- Day Content -->
                <div class="p-6">
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Nombre del día</label>
                        <input 
                            v-model="form.days[activeDayIndex].name"
                            type="text"
                            class="w-full max-w-xs 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>

                    <!-- Blocks Tabs -->
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Bloques de Ejercicios</label>
                        <div class="flex items-center gap-2 flex-wrap">
                            <button
                                v-for="(block, bIndex) in form.days[activeDayIndex].blocks"
                                :key="bIndex"
                                type="button"
                                @click="activeBlockIndex = bIndex"
                                class="px-3 py-1.5 rounded-full text-sm font-medium transition-colors relative group"
                                :class="{
                                    'bg-blue-500 text-white': activeBlockIndex === bIndex,
                                    'bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-400 hover:bg-blue-200 dark:hover:bg-blue-900/50': activeBlockIndex !== bIndex,
                                }"
                            >
                                📦 {{ block.name }}
                                <button
                                    v-if="form.days[activeDayIndex].blocks.length > 1"
                                    type="button"
                                    @click.stop="removeBlock(activeDayIndex, bIndex)"
                                    class="absolute -top-1 -right-1 w-4 h-4 bg-red-500 text-white rounded-full text-xs hidden group-hover:flex items-center justify-center"
                                >
                                    ×
                                </button>
                            </button>
                            <button
                                type="button"
                                @click="addBlock(activeDayIndex)"
                                class="px-2 py-1 text-blue-600 dark:text-blue-400 hover:bg-blue-50 dark:hover:bg-blue-900/20 rounded-full transition-colors text-sm"
                            >
                                + Bloque
                            </button>
                        </div>
                    </div>

                    <!-- Block Name Edit -->
                    <div class="mb-4">
                        <label class="block text-xs text-gray-500 dark:text-gray-400 mb-1">Nombre del bloque</label>
                        <input 
                            v-model="form.days[activeDayIndex].blocks[activeBlockIndex].name"
                            type="text"
                            class="w-full max-w-xs rounded-lg text-sm border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white focus:ring-orange-500 focus:border-orange-500"
                            placeholder="Ej: Calentamiento, Circuito A, Core..."
                        />
                    </div>

                    <!-- Exercises in Block -->
                    <div class="space-y-3">
                        <div
                            v-for="(exercise, exIndex) in form.days[activeDayIndex].blocks[activeBlockIndex].exercises"
                            :key="exIndex"
                            class="bg-gray-50 dark:bg-gray-700/50 rounded-lg p-4 border border-gray-200 dark:border-gray-600"
                        >
                            <div class="flex items-start justify-between mb-3">
                                <div class="flex items-center gap-3">
                                    <!-- GIF Preview -->
                                    <div v-if="exercise.gif_url" class="w-16 h-16 rounded-lg overflow-hidden bg-gray-200 dark:bg-gray-600 flex-shrink-0">
                                        <img :src="exercise.gif_url" :alt="exercise.name" class="w-full h-full object-cover" />
                                    </div>
                                    <div v-else class="w-16 h-16 rounded-lg bg-gray-200 dark:bg-gray-600 flex items-center justify-center flex-shrink-0">
                                        <span class="text-2xl">🏋️</span>
                                    </div>
                                    <div>
                                        <span class="text-sm font-medium text-gray-900 dark:text-white">{{ exercise.name || 'Sin nombre' }}</span>
                                        <span v-if="exercise.muscle_group" class="ml-2 px-2 py-0.5 bg-blue-100 dark:bg-blue-900/50 text-blue-700 dark:text-blue-400 text-xs rounded-full">
                                            {{ muscleGroups?.[exercise.muscle_group] || exercise.muscle_group }}
                                        </span>
                                    </div>
                                </div>
                                <div class="flex items-center gap-1">
                                    <button type="button" @click="moveExercise(activeDayIndex, activeBlockIndex, exIndex, -1)" :disabled="exIndex === 0" class="p-1 text-gray-400 hover:text-gray-600 disabled:opacity-30">↑</button>
                                    <button type="button" @click="moveExercise(activeDayIndex, activeBlockIndex, exIndex, 1)" :disabled="exIndex === form.days[activeDayIndex].blocks[activeBlockIndex].exercises.length - 1" class="p-1 text-gray-400 hover:text-gray-600 disabled:opacity-30">↓</button>
                                    <button type="button" @click="removeExercise(activeDayIndex, activeBlockIndex, exIndex)" class="p-1 text-red-500 hover:text-red-700">
                                        <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>
                            </div>
                            
                            <!-- Exercise fields -->
                            <div class="grid grid-cols-2 md:grid-cols-4 gap-3">
                                <div v-if="!exercise.exercise_id" class="col-span-2">
                                    <label class="block text-xs text-gray-500 dark:text-gray-400 mb-1">Nombre</label>
                                    <input 
                                        v-model="exercise.name"
                                        type="text"
                                        class="w-full rounded-lg text-sm border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white focus:ring-orange-500 focus:border-orange-500"
                                        placeholder="Nombre del ejercicio"
                                    />
                                </div>
                                <div>
                                    <label class="block text-xs text-gray-500 dark:text-gray-400 mb-1">Series</label>
                                    <input 
                                        v-model.number="exercise.sets"
                                        type="number"
                                        min="1"
                                        class="w-full rounded-lg text-sm border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white focus:ring-orange-500 focus:border-orange-500"
                                    />
                                </div>
                                <div>
                                    <label class="block text-xs text-gray-500 dark:text-gray-400 mb-1">Reps</label>
                                    <input 
                                        v-model="exercise.reps"
                                        type="text"
                                        class="w-full rounded-lg text-sm border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white focus:ring-orange-500 focus:border-orange-500"
                                        placeholder="10-12"
                                    />
                                </div>
                                <div>
                                    <label class="block text-xs text-gray-500 dark:text-gray-400 mb-1">Descanso (seg)</label>
                                    <input 
                                        v-model="exercise.rest"
                                        type="text"
                                        class="w-full rounded-lg text-sm border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white focus:ring-orange-500 focus:border-orange-500"
                                        placeholder="60"
                                    />
                                </div>
                            </div>
                            <div class="mt-3">
                                <label class="block text-xs text-gray-500 dark:text-gray-400 mb-1">Notas (opcional)</label>
                                <input 
                                    v-model="exercise.notes"
                                    type="text"
                                    class="w-full rounded-lg text-sm border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white focus:ring-orange-500 focus:border-orange-500"
                                    placeholder="Instrucciones adicionales..."
                                />
                            </div>
                        </div>

                        <!-- Add Exercise Buttons -->
                        <div class="flex gap-3">
                            <button
                                type="button"
                                @click="openExerciseLibrary(activeDayIndex, activeBlockIndex)"
                                class="flex-1 py-3 bg-orange-50 dark:bg-orange-900/20 border-2 border-dashed border-orange-300 dark:border-orange-700 rounded-lg text-orange-600 dark:text-orange-400 hover:bg-orange-100 dark:hover:bg-orange-900/30 transition-colors flex items-center justify-center gap-2"
                            >
                                📚 Agregar desde Biblioteca
                            </button>
                            <button
                                type="button"
                                @click="addCustomExercise(activeDayIndex, activeBlockIndex)"
                                class="flex-1 py-3 border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-lg text-gray-500 dark:text-gray-400 hover:border-gray-400 hover:text-gray-600 transition-colors flex items-center justify-center gap-2"
                            >
                                ✏️ Crear Personalizado
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Actions -->
            <div class="flex justify-end gap-3">
                <Link 
                    :href="route('coach.workouts.index')"
                    class="px-6 py-2 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
                >
                    Cancelar
                </Link>
                <button 
                    type="submit"
                    :disabled="form.processing"
                    class="px-6 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 disabled:opacity-50"
                >
                    ✨ Crear Plantilla
                </button>
            </div>
        </form>

        <!-- Exercise Library Modal -->
        <Teleport to="body">
            <div v-if="showExerciseLibrary" class="fixed inset-0 z-50 flex items-end sm:items-center justify-center" @click.self="showExerciseLibrary = false">
                <div class="fixed inset-0 bg-black/50 backdrop-blur-sm" @click="showExerciseLibrary = false"></div>
                <div class="relative bg-white dark:bg-gray-800 rounded-t-2xl sm:rounded-2xl shadow-xl w-full max-w-4xl max-h-[90vh] overflow-hidden">
                    <!-- Header -->
                    <div class="p-4 border-b border-gray-200 dark:border-gray-700">
                        <div class="flex justify-between items-center mb-4">
                            <h3 class="text-lg font-bold text-gray-900 dark:text-white">📚 Biblioteca de Ejercicios</h3>
                            <button @click="showExerciseLibrary = false" class="p-2 text-gray-400 hover:text-gray-600">✕</button>
                        </div>
                        
                        <!-- Search -->
                        <input 
                            v-model="exerciseSearch"
                            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 mb-4"
                        />
                        
                        <!-- Muscle Group Quick Filters -->
                        <div class="flex flex-wrap gap-2">
                            <button 
                                @click="selectedMuscleGroup = ''"
                                :class="[
                                    'px-3 py-1.5 rounded-full text-xs font-medium transition-all',
                                    !selectedMuscleGroup ? 'bg-orange-500 text-white' : 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-200'
                                ]"
                            >
                                Todos
                            </button>
                            <button 
                                v-for="(label, key) in muscleGroups"
                                :key="key"
                                @click="filterByMuscle(key)"
                                :class="[
                                    'px-3 py-1.5 rounded-full text-xs font-medium transition-all',
                                    selectedMuscleGroup === key ? 'bg-orange-500 text-white' : 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-200'
                                ]"
                            >
                                {{ muscleIcons[key] || '🎯' }} {{ label }}
                            </button>
                        </div>
                    </div>
                    
                    <!-- Exercise Grid -->
                    <div class="p-4 overflow-y-auto max-h-[60vh]">
                        <div v-if="filteredExercises.length" class="grid grid-cols-2 md:grid-cols-3 gap-3">
                            <button
                                v-for="exercise in filteredExercises"
                                :key="exercise.id"
                                type="button"
                                @click="addExerciseFromLibrary(exercise)"
                                class="bg-gray-50 dark:bg-gray-700/50 rounded-lg overflow-hidden hover:ring-2 hover:ring-orange-500 transition-all text-left"
                            >
                                <!-- GIF -->
                                <div v-if="exercise.gif_url" class="aspect-video bg-gray-200 dark:bg-gray-600">
                                    <img :src="exercise.gif_url" :alt="exercise.name" class="w-full h-full object-cover" 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-3xl">🏋️</span>
                                </div>
                                
                                <div class="p-3">
                                    <h4 class="font-medium text-sm text-gray-900 dark:text-white line-clamp-1">{{ exercise.name }}</h4>
                                    <div class="flex flex-wrap gap-1 mt-1">
                                        <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">
                                            {{ muscleGroups?.[exercise.muscle_group] || exercise.muscle_group }}
                                        </span>
                                        <span v-if="exercise.is_system || !exercise.coach_id" class="px-2 py-0.5 bg-gray-100 dark:bg-gray-600 text-gray-500 dark:text-gray-400 text-xs rounded-full">
                                            ✓
                                        </span>
                                    </div>
                                </div>
                            </button>
                        </div>
                        <div v-else class="text-center py-12">
                            <div class="text-4xl mb-3">🔍</div>
                            <p class="text-gray-500 dark:text-gray-400">No se encontraron ejercicios</p>
                            <Link :href="route('coach.exercises.create')" class="mt-3 inline-block text-orange-600 hover:underline">
                                + Crear nuevo ejercicio
                            </Link>
                        </div>
                    </div>
                </div>
            </div>
        </Teleport>
    </CoachLayout>
</template>
