<script setup>
import CoachLayout from '@/Layouts/CoachLayout.vue';
import { Head, Link, useForm } from '@inertiajs/vue3';
import { computed, ref, watch } from 'vue';

// Unit preferences
const weightUnit = ref('kg');
const heightUnit = ref('cm');

const form = useForm({
    name: '',
    email: '',
    phone: '',
    age: null,
    weight: null,
    height: null,
    gender: '',
    objective: 'maintain',
    activity_level: 'moderate',
    calorie_adjustment: 0,
    notes: '',
});

const submit = () => {
    form.post(route('coach.clients.store'));
};

const activityLevels = {
    sedentary: 'Sedentario (1.2x)',
    moderate: 'Moderada (1.375x)',
    active: 'Activo (1.55x)',
    very_active: 'Muy activo (1.725x)',
};

const activityMultipliers = {
    sedentary: 1.2,
    moderate: 1.375,
    active: 1.55,
    very_active: 1.725,
};

// Unit conversion helpers
const displayWeight = computed({
    get() {
        if (!form.weight) return null;
        if (weightUnit.value === 'lb') {
            return Math.round(form.weight * 2.20462);
        }
        return form.weight;
    },
    set(val) {
        if (!val) {
            form.weight = null;
            return;
        }
        if (weightUnit.value === 'lb') {
            form.weight = Math.round(val / 2.20462 * 10) / 10;
        } else {
            form.weight = val;
        }
    }
});

const displayHeight = computed({
    get() {
        if (!form.height) return null;
        if (heightUnit.value === 'm') {
            return Math.round(form.height / 100 * 100) / 100;
        } else if (heightUnit.value === 'ft') {
            // Convert cm to decimal feet (e.g., 190cm = 6.2ft)
            const totalInches = form.height / 2.54;
            const decimalFeet = totalInches / 12;
            return Math.round(decimalFeet * 10) / 10;
        }
        return form.height;
    },
    set(val) {
        if (!val) {
            form.height = null;
            return;
        }
        if (heightUnit.value === 'm') {
            form.height = Math.round(val * 100);
        } else if (heightUnit.value === 'ft') {
            // Convert decimal feet to cm (e.g., 6.3 ft = 192 cm)
            const totalInches = val * 12;
            form.height = Math.round(totalInches * 2.54);
        } else {
            form.height = val;
        }
    }
});

// Real-time BMR calculation (Mifflin-St Jeor)
const calculatedBMR = computed(() => {
    if (!form.weight || !form.height || !form.age || !form.gender) return null;
    
    if (form.gender === 'male') {
        return Math.round(10 * form.weight + 6.25 * form.height - 5 * form.age + 5);
    } else {
        return Math.round(10 * form.weight + 6.25 * form.height - 5 * form.age - 161);
    }
});

// Real-time TDEE calculation
const calculatedTDEE = computed(() => {
    if (!calculatedBMR.value || !form.activity_level) return null;
    const multiplier = activityMultipliers[form.activity_level] || 1.55;
    return Math.round(calculatedBMR.value * multiplier);
});

// Adjusted calories based on slider
const adjustedCalories = computed(() => {
    if (!calculatedTDEE.value) return null;
    const adjustment = 1 + (form.calorie_adjustment / 100);
    return Math.round(calculatedTDEE.value * adjustment);
});

// Calorie adjustment value
const calorieAdjustmentValue = computed(() => {
    if (!calculatedTDEE.value) return 0;
    return Math.round(calculatedTDEE.value * form.calorie_adjustment / 100);
});

// Real-time BMI calculation
const calculatedBMI = computed(() => {
    if (!form.weight || !form.height) return null;
    const heightM = form.height / 100;
    return (form.weight / (heightM * heightM)).toFixed(1);
});

// BMI category
const bmiCategory = computed(() => {
    if (!calculatedBMI.value) return null;
    const bmi = parseFloat(calculatedBMI.value);
    if (bmi < 18.5) return { label: 'Bajo peso', color: 'text-blue-600 bg-blue-100' };
    if (bmi < 25) return { label: 'Normal', color: 'text-green-600 bg-green-100' };
    if (bmi < 30) return { label: 'Sobrepeso', color: 'text-yellow-600 bg-yellow-100' };
    return { label: 'Obesidad', color: 'text-red-600 bg-red-100' };
});

// Check if we have enough data for calculations
const hasPhysicalData = computed(() => {
    return form.weight && form.height && form.age && form.gender;
});

// Slider gradient position
const sliderGradient = computed(() => {
    const percent = (form.calorie_adjustment + 100) / 2;
    return `linear-gradient(to right, #10b981 0%, #10b981 ${percent}%, #e5e7eb ${percent}%, #e5e7eb 100%)`;
});

// Calorie adjustment label
const calorieAdjustmentLabel = computed(() => {
    if (form.calorie_adjustment > 0) return 'Superávit Calórico';
    if (form.calorie_adjustment < 0) return 'Déficit Calórico';
    return 'Mantenimiento';
});
</script>

<template>
    <Head title="Nuevo Cliente" />

    <CoachLayout>
        <template #header>
            <div class="flex justify-between items-center">
                <h2 class="text-xl font-semibold leading-tight text-gray-800">
                    Nuevo Cliente
                </h2>
                <Link :href="route('coach.clients.index')" class="text-blue-600 hover:text-blue-900">
                    ← Volver
                </Link>
            </div>
        </template>

        <div class="py-12">
            <div class="mx-auto max-w-3xl sm:px-6 lg:px-8">
                <div class="bg-white rounded-lg shadow p-6">
                    <form @submit.prevent="submit">
                        <!-- Basic Info -->
                        <div class="mb-8">
                            <h3 class="text-lg font-semibold mb-4 pb-2 border-b">Información Básica</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 mb-1">Nombre completo *</label>
                                    <input v-model="form.name" type="text" class="w-full rounded-md border-gray-300" required />
                                    <p v-if="form.errors.name" class="text-red-500 text-sm mt-1">{{ form.errors.name }}</p>
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">Email</label>
                                    <input v-model="form.email" type="email" class="w-full rounded-md border-gray-300" />
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">Teléfono</label>
                                    <input v-model="form.phone" type="tel" class="w-full rounded-md border-gray-300" />
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">Edad</label>
                                    <input v-model.number="form.age" type="number" min="10" max="100" class="w-full rounded-md border-gray-300" />
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">Género</label>
                                    <select v-model="form.gender" class="w-full rounded-md border-gray-300">
                                        <option value="">Seleccionar...</option>
                                        <option value="male">Masculino</option>
                                        <option value="female">Femenino</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <!-- Physical Data -->
                        <div class="mb-8">
                            <h3 class="text-lg font-semibold mb-4 pb-2 border-b dark:text-white dark:border-gray-700">Datos Físicos</h3>
                            <p class="text-sm text-gray-500 dark:text-gray-400 mb-4">Estos datos se usan para calcular el metabolismo basal (BMR) y TDEE.</p>
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                                <!-- Peso -->
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Peso</label>
                                    <div class="flex gap-2">
                                        <input 
                                            v-model.number="displayWeight" 
                                            type="number" 
                                            :step="weightUnit === 'kg' ? '0.1' : '1'"
                                            :min="weightUnit === 'kg' ? '30' : '66'"
                                            :max="weightUnit === 'kg' ? '300' : '660'"
                                            class="flex-1 rounded-md border-gray-300 dark:bg-gray-700 dark:border-gray-600 dark:text-white" 
                                        />
                                        <select v-model="weightUnit" class="w-20 rounded-md border-gray-300 dark:bg-gray-700 dark:border-gray-600 dark:text-white text-sm">
                                            <option value="kg">kg</option>
                                            <option value="lb">lb</option>
                                        </select>
                                    </div>
                                </div>
                                
                                <!-- Estatura -->
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Estatura</label>
                                    <div class="flex gap-2">
                                        <!-- CM input -->
                                        <input 
                                            v-if="heightUnit === 'cm'"
                                            v-model.number="form.height" 
                                            type="number" 
                                            min="100" 
                                            max="250" 
                                            class="flex-1 rounded-md border-gray-300 dark:bg-gray-700 dark:border-gray-600 dark:text-white" 
                                        />
                                        <!-- Meters input -->
                                        <input 
                                            v-else-if="heightUnit === 'm'"
                                            v-model.number="displayHeight" 
                                            type="number"
                                            step="0.01"
                                            min="1.00" 
                                            max="2.50" 
                                            class="flex-1 rounded-md border-gray-300 dark:bg-gray-700 dark:border-gray-600 dark:text-white" 
                                        />
                                        <!-- Feet decimal input (e.g., 5.4) -->
                                        <input 
                                            v-else
                                            v-model.number="displayHeight" 
                                            type="number"
                                            step="0.1"
                                            min="3.0" 
                                            max="8.0"
                                            placeholder="5.4"
                                            class="flex-1 rounded-md border-gray-300 dark:bg-gray-700 dark:border-gray-600 dark:text-white" 
                                        />
                                        <select v-model="heightUnit" class="w-20 rounded-md border-gray-300 dark:bg-gray-700 dark:border-gray-600 dark:text-white text-sm">
                                            <option value="cm">cm</option>
                                            <option value="m">m</option>
                                            <option value="ft">pies</option>
                                        </select>
                                    </div>
                                </div>
                            </div>

                            <!-- Real-time Calculations Preview -->
                            <div v-if="hasPhysicalData || calculatedBMI" class="mt-4 p-4 bg-gradient-to-r from-indigo-50 to-purple-50 dark:from-indigo-900/20 dark:to-purple-900/20 rounded-xl border border-indigo-100 dark:border-indigo-800">
                                <h4 class="text-sm font-semibold text-indigo-700 dark:text-indigo-300 mb-3 flex items-center">
                                    <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="M9 7h6m0 10v-3m-3 3h.01M9 17h.01M9 14h.01M12 14h.01M15 11h.01M12 11h.01M9 11h.01M7 21h10a2 2 0 002-2V5a2 2 0 00-2-2H7a2 2 0 00-2 2v14a2 2 0 002 2z" />
                                    </svg>
                                    Cálculos Automáticos (Vista Previa)
                                </h4>
                                <div class="grid grid-cols-2 md:grid-cols-4 gap-3">
                                    <!-- BMI -->
                                    <div v-if="calculatedBMI" class="text-center p-3 bg-white dark:bg-gray-800 rounded-lg shadow-sm">
                                        <div class="text-2xl font-bold text-gray-800 dark:text-white">{{ calculatedBMI }}</div>
                                        <div class="text-xs text-gray-500 dark:text-gray-400">IMC</div>
                                        <span v-if="bmiCategory" :class="['text-xs px-2 py-0.5 rounded-full mt-1 inline-block', bmiCategory.color]">
                                            {{ bmiCategory.label }}
                                        </span>
                                    </div>
                                    <!-- BMR -->
                                    <div v-if="calculatedBMR" class="text-center p-3 bg-white dark:bg-gray-800 rounded-lg shadow-sm">
                                        <div class="text-2xl font-bold text-orange-600 dark:text-orange-400">{{ calculatedBMR }}</div>
                                        <div class="text-xs text-gray-500 dark:text-gray-400">BMR (kcal)</div>
                                        <div class="text-xs text-gray-400 dark:text-gray-500">Metabolismo Basal</div>
                                    </div>
                                    <!-- TDEE -->
                                    <div v-if="calculatedTDEE" class="text-center p-3 bg-white dark:bg-gray-800 rounded-lg shadow-sm">
                                        <div class="text-2xl font-bold text-green-600 dark:text-green-400">{{ calculatedTDEE }}</div>
                                        <div class="text-xs text-gray-500 dark:text-gray-400">TDEE (kcal)</div>
                                        <div class="text-xs text-gray-400 dark:text-gray-500">Gasto Diario</div>
                                    </div>
                                    <!-- Missing Data -->
                                    <div v-if="!hasPhysicalData" class="text-center p-3 bg-gray-100 dark:bg-gray-700 rounded-lg col-span-2 md:col-span-1">
                                        <div class="text-xs text-gray-500 dark:text-gray-400">
                                            <svg class="w-6 h-6 mx-auto mb-1 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                                            </svg>
                                            Completa edad, peso, altura y género para calcular BMR y TDEE
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Goals & Activity -->
                        <div class="mb-8">
                            <h3 class="text-lg font-semibold mb-4 pb-2 border-b">Objetivos y Actividad</h3>
                            
                            <!-- Activity Level -->
                            <div class="mb-6">
                                <label class="block text-sm font-medium text-gray-700 mb-2">Nivel de actividad</label>
                                <select v-model="form.activity_level" class="w-full rounded-md border-gray-300">
                                    <option v-for="(label, key) in activityLevels" :key="key" :value="key">
                                        {{ label }}
                                    </option>
                                </select>
                            </div>
                            
                            <!-- Calorie Adjustment Slider -->
                            <div class="bg-gradient-to-br from-green-50 to-emerald-50 dark:from-green-900/20 dark:to-emerald-900/20 rounded-xl p-5 border border-green-200 dark:border-green-700">
                                <div class="flex items-center justify-between mb-3">
                                    <label class="text-sm font-medium text-gray-700 dark:text-gray-300 flex items-center gap-2">
                                        Ajuste de calorías
                                        <span class="inline-flex items-center justify-center w-4 h-4 text-xs text-gray-400 border border-gray-300 rounded-full cursor-help" title="Ajusta las calorías según las necesidades específicas del cliente">ⓘ</span>
                                    </label>
                                    <div class="flex items-center gap-2">
                                        <span v-if="form.calorie_adjustment !== 0" :class="[
                                            'text-xs font-medium px-2 py-1 rounded-full flex items-center gap-1',
                                            form.calorie_adjustment > 0 ? 'bg-green-100 text-green-700 dark:bg-green-800 dark:text-green-300' : 'bg-red-100 text-red-700 dark:bg-red-800 dark:text-red-300'
                                        ]">
                                            <span>→</span>
                                            {{ calorieAdjustmentLabel }}
                                        </span>
                                        <span class="text-lg font-bold" :class="[
                                            form.calorie_adjustment > 0 ? 'text-green-600' : form.calorie_adjustment < 0 ? 'text-red-600' : 'text-gray-700'
                                        ]">{{ form.calorie_adjustment > 0 ? '+' : '' }}{{ form.calorie_adjustment }}%</span>
                                    </div>
                                </div>
                                
                                <!-- Slider -->
                                <div class="relative mt-2 mb-3">
                                    <input 
                                        type="range" 
                                        v-model.number="form.calorie_adjustment"
                                        min="-100" 
                                        max="100" 
                                        step="1"
                                        class="w-full h-3 rounded-lg appearance-none cursor-pointer slider-green"
                                        :style="{ background: sliderGradient }"
                                    />
                                    <div class="flex justify-between text-xs text-gray-500 dark:text-gray-400 mt-2">
                                        <span class="text-red-500">-100%</span>
                                        <span class="text-gray-400">0%</span>
                                        <span class="text-green-500">+100%</span>
                                    </div>
                                </div>
                                
                                <!-- TDEE Info Table -->
                                <div v-if="calculatedTDEE" class="mt-4 bg-white dark:bg-gray-800 rounded-lg p-4 shadow-sm">
                                    <div class="space-y-3">
                                        <div class="flex justify-between items-center py-2 border-b border-gray-100 dark:border-gray-700">
                                            <span class="text-sm text-gray-600 dark:text-gray-400">TDEE:</span>
                                            <span class="font-semibold text-gray-900 dark:text-white">{{ calculatedTDEE }} kcal</span>
                                        </div>
                                        <div class="flex justify-between items-center py-2 border-b border-gray-100 dark:border-gray-700">
                                            <span class="text-sm text-gray-600 dark:text-gray-400">Ajuste:</span>
                                            <span :class="[
                                                'font-semibold',
                                                calorieAdjustmentValue > 0 ? 'text-green-600' : calorieAdjustmentValue < 0 ? 'text-red-600' : 'text-gray-600'
                                            ]">
                                                {{ calorieAdjustmentValue > 0 ? '+' : '' }}{{ calorieAdjustmentValue }} kcal
                                            </span>
                                        </div>
                                        <div class="flex justify-between items-center pt-2">
                                            <span class="font-medium text-gray-700 dark:text-gray-300">Calorías:</span>
                                            <span class="font-bold text-xl text-green-600 dark:text-green-400">{{ adjustedCalories }} kcal</span>
                                        </div>
                                    </div>
                                </div>
                                <div v-else class="mt-4 bg-white/50 dark:bg-gray-800/50 rounded-lg p-4 text-center text-sm text-gray-500">
                                    Completa los datos físicos para ver el cálculo de calorías
                                </div>
                            </div>
                        </div>

                        <!-- Notes -->
                        <div class="mb-8">
                            <label class="block text-sm font-medium text-gray-700 mb-1">Notas adicionales</label>
                            <textarea v-model="form.notes" rows="3" class="w-full rounded-md border-gray-300" placeholder="Lesiones, alergias, preferencias..."></textarea>
                        </div>

                        <!-- Submit -->
                        <div class="flex gap-3">
                            <Link :href="route('coach.clients.index')" class="flex-1 py-2 text-center border rounded-lg hover:bg-gray-50">
                                Cancelar
                            </Link>
                            <button
                                type="submit"
                                :disabled="form.processing"
                                class="flex-1 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50"
                            >
                                Crear Cliente
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </CoachLayout>
</template>

<style scoped>
/* Custom slider styling */
.slider-green::-webkit-slider-thumb {
    -webkit-appearance: none;
    appearance: none;
    width: 20px;
    height: 20px;
    border-radius: 50%;
    background: white;
    border: 2px solid #10b981;
    cursor: pointer;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.slider-green::-moz-range-thumb {
    width: 20px;
    height: 20px;
    border-radius: 50%;
    background: white;
    border: 2px solid #10b981;
    cursor: pointer;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
</style>
