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

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

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

const deletePlan = (plan) => {
    if (confirm(`¿Eliminar el plan "${plan.name}"?`)) {
        router.delete(route('coach.clients.meal-plans.destroy', [props.client.id, plan.id]));
    }
};

// Format date
const formatDate = (dateString) => {
    if (!dateString) return '';
    const date = new Date(dateString);
    return date.toLocaleDateString('es-ES', { 
        day: '2-digit', 
        month: '2-digit', 
        year: 'numeric' 
    });
};

// Calculate TDEE percentage
const getTdeePercentage = (calories) => {
    if (!props.client?.tdee) return null;
    const percentage = ((calories / props.client.tdee) * 100).toFixed(0);
    return percentage;
};

// Calculate macro distribution percentages (P*4 + C*4 + G*9)
const getMacroDistribution = (totals) => {
    if (!totals) return { protein: 33, carbs: 33, fats: 34 };
    
    const proteinCals = (totals.proteins || 0) * 4;
    const carbsCals = (totals.carbs || 0) * 4;
    const fatsCals = (totals.fats || 0) * 9;
    const totalCals = proteinCals + carbsCals + fatsCals;
    
    if (totalCals === 0) return { protein: 33, carbs: 33, fats: 34 };
    
    return {
        protein: Math.round((proteinCals / totalCals) * 100),
        carbs: Math.round((carbsCals / totalCals) * 100),
        fats: Math.round((fatsCals / totalCals) * 100),
    };
};
</script>

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

    <CoachLayout>
        <template #header>
            <div class="flex justify-between items-center">
                <div class="flex items-center gap-3">
                    <Link :href="route('coach.clients.show', client.id)" 
                        class="p-2 text-gray-500 hover:text-gray-700 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="M15 19l-7-7 7-7" />
                        </svg>
                    </Link>
                    <!-- Client selector dropdown style -->
                    <div class="flex items-center gap-2 px-3 py-1.5 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg">
                        <span class="font-medium text-gray-900 dark:text-white">{{ client.name }}</span>
                        <svg class="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 9l4-4 4 4m0 6l-4 4-4-4" />
                        </svg>
                    </div>
                </div>
                <h2 class="text-xl font-bold text-gray-900 dark:text-white">
                    Planes de {{ client.name }}
                </h2>
                <Link 
                    :href="route('coach.clients.meal-plans.create', client.id)"
                    class="hidden lg:flex px-4 py-2 bg-gray-900 dark:bg-white text-white dark:text-gray-900 rounded-lg hover:bg-gray-800 dark:hover:bg-gray-100 items-center gap-2 font-medium"
                >
                    <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 4v16m8-8H4" />
                    </svg>
                    Crear Plan
                </Link>
            </div>
        </template>

        <PullToRefresh :loading="isRefreshing" @refresh="handleRefresh">
        <div class="py-4 sm:py-8">
            <div class="mx-auto max-w-7xl sm:px-6 lg:px-8">
                <div v-if="mealPlans.length" class="space-y-6">
                    <div 
                        v-for="plan in mealPlans" 
                        :key="plan.id"
                        class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-100 dark:border-gray-700 overflow-hidden"
                    >
                        <div class="p-6">
                            <!-- Header Row -->
                            <div class="flex justify-between items-start mb-6">
                                <div>
                                    <h3 class="text-lg font-bold text-gray-900 dark:text-white">
                                        Meal Plan - {{ client.name }} ({{ formatDate(plan.created_at) }}) #{{ plan.id }}
                                    </h3>
                                    <p class="text-sm text-gray-500 dark:text-gray-400 mt-0.5">
                                        Creado el {{ formatDate(plan.created_at) }}
                                    </p>
                                </div>
                                
                                <!-- Action Buttons -->
                                <div class="flex flex-wrap items-center gap-2">
                                    <Link 
                                        :href="route('coach.clients.meal-plans.show', [client.id, plan.id])"
                                        class="px-4 py-2 text-sm bg-gradient-to-r from-green-500 to-emerald-600 text-white rounded-lg hover:from-green-600 hover:to-emerald-700 flex items-center gap-2 font-medium shadow-sm"
                                    >
                                        <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="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                                        </svg>
                                        Ver
                                    </Link>
                                    <a 
                                        :href="route('coach.clients.meal-plans.pdf', [client.id, plan.id]) + '?lang=es'"
                                        class="px-3 py-2 text-sm border border-gray-200 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 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>
                                        Descargar PDF
                                    </a>
                                    <Link 
                                        :href="route('coach.clients.meal-plans.show', [client.id, plan.id])"
                                        class="px-3 py-2 text-sm border border-gray-200 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 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="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                                        </svg>
                                        Ver
                                    </Link>
                                    <button 
                                        @click="deletePlan(plan)"
                                        class="p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-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="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                                        </svg>
                                    </button>
                                </div>
                            </div>

                            <!-- Macros Summary Bar -->
                            <div class="bg-gray-50 dark:bg-gray-700/50 rounded-xl p-5">
                                <div class="grid grid-cols-4 gap-6 mb-5">
                                    <!-- Calories -->
                                    <div class="text-center">
                                        <div class="text-3xl font-bold text-gray-900 dark:text-white">{{ Math.round(plan.totals?.calories || 0) }}</div>
                                        <div class="text-sm text-gray-500 dark:text-gray-400">kcal</div>
                                        <div v-if="getTdeePercentage(plan.totals?.calories)" class="text-xs text-gray-400 dark:text-gray-500 mt-1">
                                            {{ getTdeePercentage(plan.totals?.calories) }}% TDEE
                                        </div>
                                    </div>
                                    <!-- Proteins -->
                                    <div class="text-center">
                                        <div class="text-3xl font-bold text-teal-500">{{ Math.round(plan.totals?.proteins || 0) }}g</div>
                                        <div class="text-sm text-gray-500 dark:text-gray-400">Proteínas</div>
                                        <div class="text-xs text-gray-400 dark:text-gray-500 mt-1">
                                            {{ getMacroDistribution(plan.totals).protein }}%
                                        </div>
                                    </div>
                                    <!-- Carbs -->
                                    <div class="text-center">
                                        <div class="text-3xl font-bold text-orange-500">{{ Math.round(plan.totals?.carbs || 0) }}g</div>
                                        <div class="text-sm text-gray-500 dark:text-gray-400">Carbohidratos</div>
                                        <div class="text-xs text-gray-400 dark:text-gray-500 mt-1">
                                            {{ getMacroDistribution(plan.totals).carbs }}%
                                        </div>
                                    </div>
                                    <!-- Fats -->
                                    <div class="text-center">
                                        <div class="text-3xl font-bold text-purple-500">{{ Math.round(plan.totals?.fats || 0) }}g</div>
                                        <div class="text-sm text-gray-500 dark:text-gray-400">Grasas</div>
                                        <div class="text-xs text-gray-400 dark:text-gray-500 mt-1">
                                            {{ getMacroDistribution(plan.totals).fats }}%
                                        </div>
                                    </div>
                                </div>

                                <!-- Macro Distribution Bar -->
                                <div>
                                    <div class="text-xs text-gray-500 dark:text-gray-400 mb-2">Distribución de macronutrientes</div>
                                    <div class="h-3 rounded-full overflow-hidden flex bg-gray-200 dark:bg-gray-600">
                                        <div 
                                            class="bg-teal-500 transition-all"
                                            :style="{ width: getMacroDistribution(plan.totals).protein + '%' }"
                                        ></div>
                                        <div 
                                            class="bg-orange-500 transition-all"
                                            :style="{ width: getMacroDistribution(plan.totals).carbs + '%' }"
                                        ></div>
                                        <div 
                                            class="bg-purple-500 transition-all"
                                            :style="{ width: getMacroDistribution(plan.totals).fats + '%' }"
                                        ></div>
                                    </div>
                                </div>
                            </div>
                        </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="text-6xl mb-4">🥗</div>
                    <h3 class="text-xl font-bold text-gray-900 dark:text-white mb-2">No hay planes de alimentación</h3>
                    <p class="text-gray-500 dark:text-gray-400 mb-6">Crea el primer plan de alimentación para {{ client.name }}</p>
                    <Link 
                        :href="route('coach.clients.meal-plans.create', client.id)"
                        class="inline-block px-6 py-3 bg-gray-900 dark:bg-white text-white dark:text-gray-900 rounded-xl font-semibold hover:bg-gray-800 dark:hover:bg-gray-100"
                    >
                        + Crear Plan
                    </Link>
                </div>
            </div>
        </div>
        </PullToRefresh>

        <!-- Mobile FAB -->
        <FloatingActionButton
            class="lg:hidden"
            icon="plus"
            label="Crear Plan"
            color="green"
            :extended="true"
            @click="$inertia.visit(route('coach.clients.meal-plans.create', client.id))"
        />
    </CoachLayout>
</template>
