<script setup>
/**
 * Coach View Workout Detail
 * Displays a workout with all exercises organized by day
 */
import CoachLayout from '@/Layouts/CoachLayout.vue';
import { Head, Link, router } from '@inertiajs/vue3';
import { computed } from 'vue';

const props = defineProps({
    client: Object,
    workout: Object,
});

// Days of the week mapping
const dayLabels = {
    LUN: 'Lunes',
    MAR: 'Martes',
    MIE: 'Miércoles',
    JUE: 'Jueves',
    VIE: 'Viernes',
    SAB: 'Sábado',
    DOM: 'Domingo',
    // Legacy support
    monday: 'Lunes',
    tuesday: 'Martes',
    wednesday: 'Miércoles',
    thursday: 'Jueves',
    friday: 'Viernes',
    saturday: 'Sábado',
    sunday: 'Domingo',
};

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

// Group exercises by day
const exercisesByDay = computed(() => {
    const grouped = {};
    if (!props.workout?.exercises) return grouped;

    props.workout.exercises.forEach(ex => {
        const day = ex.day || 'general';
        if (!grouped[day]) {
            grouped[day] = [];
        }
        grouped[day].push(ex);
    });

    // Sort by order within each day
    Object.keys(grouped).forEach(day => {
        grouped[day].sort((a, b) => (a.order || 0) - (b.order || 0));
    });

    return grouped;
});

// Get active days from workout
const activeDays = computed(() => {
    return props.workout?.days || [];
});

// Total exercises
const totalExercises = computed(() => {
    return props.workout?.exercises?.length || 0;
});

const toggleActive = () => {
    router.post(route('coach.clients.workouts.toggle', {
        client: props.client.id,
        workout: props.workout.id
    }), {}, {
        preserveScroll: true,
    });
};

const downloadPdf = () => {
    window.open(route('coach.clients.workouts.pdf', {
        client: props.client.id,
        workout: props.workout.id
    }), '_blank');
};
</script>

<template>
    <Head :title="`${workout.name} - ${client.name}`" />

    <CoachLayout>
        <template #header>
            <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                <div class="flex items-center gap-4">
                    <Link
                        :href="route('coach.clients.workouts.index', client.id)"
                        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>
                        <div class="flex items-center gap-2">
                            <h2 class="text-xl font-bold text-gray-900 dark:text-white">🏋️ {{ workout.name }}</h2>
                            <span
                                v-if="workout.is_active"
                                class="px-2 py-0.5 bg-green-100 dark:bg-green-900/30 text-green-800 dark:text-green-400 text-xs font-medium rounded-full"
                            >
                                Activa
                            </span>
                        </div>
                        <p class="text-sm text-gray-500 dark:text-gray-400">Para {{ client.name }}</p>
                    </div>
                </div>
                <div class="flex items-center gap-2">
                    <button
                        @click="downloadPdf"
                        class="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-600 flex items-center gap-2"
                    >
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                        </svg>
                        PDF
                    </button>
                    <Link
                        :href="route('coach.clients.workouts.edit', { client: client.id, workout: workout.id })"
                        class="px-4 py-2 text-sm font-medium text-white bg-orange-600 hover:bg-orange-700 rounded-lg flex items-center gap-2"
                    >
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                        </svg>
                        Editar
                    </Link>
                </div>
            </div>
        </template>

        <div class="py-6">
            <div class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
                <!-- Workout Info Card -->
                <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-100 dark:border-gray-700 p-6 mb-6">
                    <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                        <div>
                            <p v-if="workout.description" class="text-gray-600 dark:text-gray-400 mb-3">{{ workout.description }}</p>

                            <!-- Days -->
                            <div class="flex flex-wrap gap-2">
                                <span class="text-sm text-gray-500 dark:text-gray-400 mr-2">📅 Días:</span>
                                <span
                                    v-for="day in activeDays"
                                    :key="day"
                                    class="px-2 py-0.5 bg-orange-100 dark:bg-orange-900/30 text-orange-800 dark:text-orange-400 text-xs font-medium rounded"
                                >
                                    {{ dayLabels[day] || day }}
                                </span>
                                <span v-if="activeDays.length === 0" class="text-sm text-gray-400">Sin días asignados</span>
                            </div>
                        </div>

                        <div class="flex items-center gap-4">
                            <div class="text-center">
                                <div class="text-2xl font-bold text-orange-600">{{ totalExercises }}</div>
                                <div class="text-xs text-gray-500 dark:text-gray-400">Ejercicios</div>
                            </div>
                            <button
                                @click="toggleActive"
                                :class="[
                                    'px-4 py-2 rounded-lg text-sm font-medium transition-colors',
                                    workout.is_active
                                        ? 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600'
                                        : 'bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-400 hover:bg-green-200'
                                ]"
                            >
                                {{ workout.is_active ? 'Desactivar' : 'Activar' }}
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Exercises by Day -->
                <div v-if="Object.keys(exercisesByDay).length > 0" class="space-y-6">
                    <div
                        v-for="(exercises, day) in exercisesByDay"
                        :key="day"
                        class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-100 dark:border-gray-700 overflow-hidden"
                    >
                        <div class="bg-gradient-to-r from-orange-500 to-red-500 px-6 py-3">
                            <h3 class="text-lg font-semibold text-white">
                                📅 {{ dayLabels[day] || day === 'general' ? 'General' : day }}
                            </h3>
                            <p class="text-sm text-orange-100">{{ exercises.length }} ejercicio(s)</p>
                        </div>

                        <div class="divide-y divide-gray-100 dark:divide-gray-700">
                            <div
                                v-for="(exercise, index) in exercises"
                                :key="exercise.id"
                                class="p-4 hover:bg-gray-50 dark:hover:bg-gray-700/30 transition-colors"
                            >
                                <div class="flex items-start gap-4">
                                    <!-- Exercise Image/Icon -->
                                    <div v-if="exercise.gif_url" class="w-20 h-20 rounded-lg overflow-hidden bg-gray-200 dark:bg-gray-700 flex-shrink-0">
                                        <img :src="exercise.gif_url" :alt="exercise.name" class="w-full h-full object-cover" loading="lazy" />
                                    </div>
                                    <div v-else class="w-20 h-20 rounded-lg bg-orange-100 dark:bg-orange-900/30 flex items-center justify-center text-3xl flex-shrink-0">
                                        {{ muscleIcons[exercise.muscle_group] || '🏋️' }}
                                    </div>

                                    <!-- Exercise Info -->
                                    <div class="flex-1 min-w-0">
                                        <div class="flex items-start justify-between gap-2">
                                            <div>
                                                <h4 class="font-semibold text-gray-900 dark:text-white">{{ exercise.name }}</h4>
                                                <span v-if="exercise.muscle_group" class="inline-block px-2 py-0.5 bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-400 text-xs rounded-full mt-1">
                                                    {{ exercise.muscle_group }}
                                                </span>
                                            </div>
                                            <span class="text-sm text-gray-400 dark:text-gray-500">#{{ index + 1 }}</span>
                                        </div>

                                        <!-- Exercise Details -->
                                        <div class="flex flex-wrap gap-4 mt-3">
                                            <div class="flex items-center gap-2">
                                                <span class="text-orange-500 text-lg">📊</span>
                                                <div>
                                                    <span class="text-lg font-bold text-gray-900 dark:text-white">{{ exercise.sets }}</span>
                                                    <span class="text-sm text-gray-500 dark:text-gray-400"> series</span>
                                                </div>
                                            </div>
                                            <div class="flex items-center gap-2">
                                                <span class="text-orange-500 text-lg">🔄</span>
                                                <div>
                                                    <span class="text-lg font-bold text-gray-900 dark:text-white">{{ exercise.reps }}</span>
                                                    <span class="text-sm text-gray-500 dark:text-gray-400"> reps</span>
                                                </div>
                                            </div>
                                            <div v-if="exercise.rest_seconds" class="flex items-center gap-2">
                                                <span class="text-orange-500 text-lg">⏱️</span>
                                                <div>
                                                    <span class="text-lg font-bold text-gray-900 dark:text-white">{{ exercise.rest_seconds }}s</span>
                                                    <span class="text-sm text-gray-500 dark:text-gray-400"> descanso</span>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Notes -->
                                        <p v-if="exercise.notes" class="text-sm text-gray-500 dark:text-gray-400 mt-2 italic">
                                            💡 {{ exercise.notes }}
                                        </p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Empty State -->
                <div v-else class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-100 dark:border-gray-700 p-12 text-center">
                    <span class="text-5xl mb-4 block">🏋️</span>
                    <h3 class="text-lg font-medium text-gray-900 dark:text-white mb-2">Sin ejercicios</h3>
                    <p class="text-gray-500 dark:text-gray-400 mb-4">Esta rutina no tiene ejercicios asignados aún.</p>
                    <Link
                        :href="route('coach.clients.workouts.edit', { client: client.id, workout: workout.id })"
                        class="inline-flex items-center px-4 py-2 bg-orange-600 text-white rounded-lg hover:bg-orange-700"
                    >
                        <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
                        </svg>
                        Agregar Ejercicios
                    </Link>
                </div>
            </div>
        </div>
    </CoachLayout>
</template>
