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

const props = defineProps({
    user: Object,
    plans: Array,
});

const form = useForm({
    name: props.user.name,
    email: props.user.email,
    password: '',
    password_confirmation: '',
    phone: props.user.phone || '',
    status: props.user.status,
    plan_id: props.user.active_subscription?.plan_id || '',
    plan_duration_days: props.user.active_subscription ? Math.ceil((new Date(props.user.active_subscription.end_date) - new Date()) / (1000 * 60 * 60 * 24)) : 30,
});

// Watch for plan changes and update duration automatically
watch(() => form.plan_id, (newPlanId) => {
    if (newPlanId) {
        const selectedPlan = props.plans.find(p => p.id === newPlanId);
        if (selectedPlan) {
            form.plan_duration_days = selectedPlan.duration_days;
        }
    } else {
        form.plan_duration_days = 30;
    }
});

const submit = () => {
    form.put(route('admin.users.update', props.user.id));
};

const statusConfig = {
    active: { color: 'bg-green-100 dark:bg-green-900/30 text-green-800 dark:text-green-400', label: 'Activo' },
    pending: { color: 'bg-yellow-100 dark:bg-yellow-900/30 text-yellow-800 dark:text-yellow-400', label: 'Pendiente' },
    suspended: { color: 'bg-red-100 dark:bg-red-900/30 text-red-800 dark:text-red-400', label: 'Suspendido' },
};

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

<template>
    <Head :title="`Editar Coach - ${user.name}`" />

    <AdminLayout>
        <div class="py-6">
            <!-- Header -->
            <div class="mb-8 px-4 sm:px-0">
                <div class="flex items-center justify-between">
                    <div class="flex items-center space-x-4">
                        <Link :href="route('admin.users.index')" class="p-2 bg-gray-100 dark:bg-gray-700 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors">
                            <svg class="w-5 h-5 text-gray-600 dark:text-gray-400" 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>
                            <h1 class="text-2xl font-bold text-gray-900 dark:text-white">Editar Coach</h1>
                            <p class="text-gray-500 dark:text-gray-400">{{ user.name }} - {{ user.email }}</p>
                        </div>
                    </div>
                    <span :class="[statusConfig[user.status]?.color, 'px-3 py-1 text-sm font-medium rounded-full']">
                        {{ statusConfig[user.status]?.label }}
                    </span>
                </div>
            </div>

            <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                <!-- Form Card -->
                <div class="lg:col-span-2 bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-100 dark:border-gray-700">
                    <form @submit.prevent="submit" class="p-6 space-y-6">
                        <!-- Datos Básicos -->
                        <div class="border-b border-gray-200 dark:border-gray-700 pb-6">
                            <h3 class="text-lg font-medium text-gray-900 dark:text-white mb-4">Información Personal</h3>
                            
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                                        Nombre Completo *
                                    </label>
                                    <input
                                        v-model="form.name"
                                        type="text"
                                        required
                                        class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white focus:ring-blue-500 focus:border-blue-500"
                                    />
                                    <p v-if="form.errors.name" class="mt-1 text-sm text-red-600 dark:text-red-400">{{ form.errors.name }}</p>
                                </div>

                                <div>
                                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                                        Email *
                                    </label>
                                    <input
                                        v-model="form.email"
                                        type="email"
                                        required
                                        class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white focus:ring-blue-500 focus:border-blue-500"
                                    />
                                    <p v-if="form.errors.email" class="mt-1 text-sm text-red-600 dark:text-red-400">{{ form.errors.email }}</p>
                                </div>

                                <div>
                                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                                        Teléfono
                                    </label>
                                    <input
                                        v-model="form.phone"
                                        type="tel"
                                        class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white focus:ring-blue-500 focus:border-blue-500"
                                        placeholder="+1 234 567 8900"
                                    />
                                    <p v-if="form.errors.phone" class="mt-1 text-sm text-red-600 dark:text-red-400">{{ form.errors.phone }}</p>
                                </div>

                                <div>
                                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                                        Estado
                                    </label>
                                    <select
                                        v-model="form.status"
                                        class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white focus:ring-blue-500 focus:border-blue-500"
                                    >
                                        <option value="active">Activo</option>
                                        <option value="pending">Pendiente</option>
                                        <option value="suspended">Suspendido</option>
                                    </select>
                                    <p v-if="form.errors.status" class="mt-1 text-sm text-red-600 dark:text-red-400">{{ form.errors.status }}</p>
                                </div>
                            </div>
                        </div>

                        <!-- Plan de Suscripción -->
                        <div class="border-b border-gray-200 dark:border-gray-700 pb-6">
                            <h3 class="text-lg font-medium text-gray-900 dark:text-white mb-4">Plan de Suscripción</h3>
                            <p class="text-sm text-gray-500 dark:text-gray-400 mb-4">Asigna o cambia el plan del coach</p>
                            
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                                        Plan
                                    </label>
                                    <select
                                        v-model="form.plan_id"
                                        class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white focus:ring-blue-500 focus:border-blue-500"
                                    >
                                        <option value="">Sin plan</option>
                                        <option v-for="plan in plans" :key="plan.id" :value="plan.id">
                                            {{ plan.name }} - ${{ plan.price }} ({{ plan.duration_days }} días)
                                        </option>
                                    </select>
                                    <p v-if="form.errors.plan_id" class="mt-1 text-sm text-red-600 dark:text-red-400">{{ form.errors.plan_id }}</p>
                                </div>

                                <div>
                                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                                        Duración (días)
                                    </label>
                                    <input
                                        v-model.number="form.plan_duration_days"
                                        type="number"
                                        min="1"
                                        max="365"
                                        :disabled="!form.plan_id"
                                        class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white focus:ring-blue-500 focus:border-blue-500 disabled:opacity-50"
                                    />
                                    <p v-if="form.errors.plan_duration_days" class="mt-1 text-sm text-red-600 dark:text-red-400">{{ form.errors.plan_duration_days }}</p>
                                </div>
                            </div>

                            <div v-if="user.active_subscription" class="mt-4 p-4 bg-blue-50 dark:bg-blue-900/20 rounded-lg">
                                <p class="text-sm text-blue-700 dark:text-blue-300">
                                    <strong>Plan actual:</strong> {{ user.active_subscription.plan?.name || 'N/A' }} - 
                                    Vence: {{ formatDate(user.active_subscription.end_date) }}
                                </p>
                                <p class="text-xs text-blue-600 dark:text-blue-400 mt-1">
                                    Al cambiar el plan se creará una nueva suscripción.
                                </p>
                            </div>
                        </div>

                        <!-- Contraseña -->
                        <div class="pb-6">
                            <h3 class="text-lg font-medium text-gray-900 dark:text-white mb-4">Cambiar Contraseña</h3>
                            <p class="text-sm text-gray-500 dark:text-gray-400 mb-4">Deja estos campos vacíos si no deseas cambiar la contraseña</p>
                            
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                                        Nueva Contraseña
                                    </label>
                                    <input
                                        v-model="form.password"
                                        type="password"
                                        class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white focus:ring-blue-500 focus:border-blue-500"
                                        placeholder="••••••••"
                                    />
                                    <p v-if="form.errors.password" class="mt-1 text-sm text-red-600 dark:text-red-400">{{ form.errors.password }}</p>
                                </div>

                                <div>
                                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                                        Confirmar Contraseña
                                    </label>
                                    <input
                                        v-model="form.password_confirmation"
                                        type="password"
                                        class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white focus:ring-blue-500 focus:border-blue-500"
                                        placeholder="••••••••"
                                    />
                                </div>
                            </div>
                        </div>

                        <!-- Actions -->
                        <div class="flex items-center justify-end space-x-4 pt-4 border-t border-gray-200 dark:border-gray-700">
                            <Link
                                :href="route('admin.users.index')"
                                class="px-4 py-2 text-gray-700 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white transition-colors"
                            >
                                Cancelar
                            </Link>
                            <button
                                type="submit"
                                :disabled="form.processing"
                                class="px-6 py-2 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                            >
                                <span v-if="form.processing">Guardando...</span>
                                <span v-else>Guardar Cambios</span>
                            </button>
                        </div>
                    </form>
                </div>

                <!-- Info Panel -->
                <div class="space-y-6">
                    <!-- Subscription 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-medium text-gray-900 dark:text-white mb-4">Suscripción</h3>
                        
                        <div v-if="user.active_subscription">
                            <div class="flex items-center justify-between mb-3">
                                <span class="text-gray-500 dark:text-gray-400">Plan:</span>
                                <span class="font-medium text-gray-900 dark:text-white">{{ user.active_subscription.plan?.name || 'N/A' }}</span>
                            </div>
                            <div class="flex items-center justify-between mb-3">
                                <span class="text-gray-500 dark:text-gray-400">Estado:</span>
                                <span class="px-2 py-1 text-xs font-medium rounded-full bg-green-100 dark:bg-green-900/30 text-green-800 dark:text-green-400">
                                    {{ user.active_subscription.status }}
                                </span>
                            </div>
                            <div class="flex items-center justify-between">
                                <span class="text-gray-500 dark:text-gray-400">Vence:</span>
                                <span class="font-medium text-gray-900 dark:text-white">{{ formatDate(user.active_subscription.end_date) }}</span>
                            </div>
                        </div>
                        <div v-else class="text-center py-4">
                            <p class="text-gray-500 dark:text-gray-400">Sin suscripción activa</p>
                        </div>
                    </div>

                    <!-- Quick 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-medium text-gray-900 dark:text-white mb-4">Información</h3>
                        
                        <div class="space-y-3">
                            <div class="flex items-center justify-between">
                                <span class="text-gray-500 dark:text-gray-400">Registrado:</span>
                                <span class="font-medium text-gray-900 dark:text-white">{{ formatDate(user.created_at) }}</span>
                            </div>
                            <div class="flex items-center justify-between">
                                <span class="text-gray-500 dark:text-gray-400">Última actividad:</span>
                                <span class="font-medium text-gray-900 dark:text-white">{{ user.last_login_at ? formatDate(user.last_login_at) : 'N/A' }}</span>
                            </div>
                        </div>
                    </div>

                    <!-- Actions -->
                    <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-medium text-gray-900 dark:text-white mb-4">Acciones</h3>
                        
                        <div class="space-y-3">
                            <Link
                                :href="route('admin.users.show', user.id)"
                                class="w-full flex items-center justify-center px-4 py-2 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-300 font-medium rounded-lg transition-colors"
                            >
                                Ver Perfil Completo
                            </Link>
                            <Link
                                :href="route('admin.users.clients', user.id)"
                                class="w-full flex items-center justify-center px-4 py-2 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-300 font-medium rounded-lg transition-colors"
                            >
                                Ver Clientes
                            </Link>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </AdminLayout>
</template>
