<script setup>
import { ref, computed, onMounted } from 'vue';
import { router, usePage } from '@inertiajs/vue3';
import { Menu, MenuButton, MenuItem, MenuItems } from '@headlessui/vue';
import { BellIcon } from '@heroicons/vue/24/outline';
import { BellAlertIcon } from '@heroicons/vue/24/solid';

const page = usePage();
const notifications = ref([]);
const unreadCount = ref(0);
const loading = ref(false);

// Cargar notificaciones
const fetchNotifications = async () => {
    try {
        loading.value = true;
        const response = await fetch(route('notifications.fetch'), {
            headers: {
                'Accept': 'application/json',
                'X-Requested-With': 'XMLHttpRequest',
            },
        });
        
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        
        const data = await response.json();
        notifications.value = data.notifications || [];
        unreadCount.value = data.unreadCount || 0;
    } catch (error) {
    } finally {
        loading.value = false;
    }
};

// Marcar como leída
const markAsRead = async (notificationId) => {
    try {
        await fetch(route('notifications.read', notificationId), {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content || '',
            },
        });
        
        // Actualizar localmente
        const notification = notifications.value.find(n => n.id === notificationId);
        if (notification) {
            notification.read_at = new Date().toISOString();
            unreadCount.value = Math.max(0, unreadCount.value - 1);
        }
    } catch (error) {
    }
};

// Marcar todas como leídas
const markAllAsRead = async () => {
    try {
        await fetch(route('notifications.read-all'), {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content || '',
            },
        });
        
        notifications.value.forEach(n => n.read_at = new Date().toISOString());
        unreadCount.value = 0;
    } catch (error) {
    }
};

// Manejar click en notificación
const handleNotificationClick = (notification) => {
    markAsRead(notification.id);
    
    if (notification.data?.url) {
        router.visit(notification.data.url);
    }
};

// Formato de tiempo relativo
const timeAgo = (date) => {
    const now = new Date();
    const past = new Date(date);
    const seconds = Math.floor((now - past) / 1000);
    
    if (seconds < 60) return 'Ahora';
    if (seconds < 3600) return `Hace ${Math.floor(seconds / 60)} min`;
    if (seconds < 86400) return `Hace ${Math.floor(seconds / 3600)} h`;
    if (seconds < 604800) return `Hace ${Math.floor(seconds / 86400)} días`;
    return past.toLocaleDateString('es-ES');
};

// Icono según tipo de notificación
const getNotificationIcon = (type) => {
    const icons = {
        'new_message': '💬',
        'coach_registered': '👤',
        'coach_approved': '✅',
        'invoice_generated': '📄',
        'payment_problem': '⚠️',
        'payment_reminder': '🔔',
        'subscription_activated': '🎉',
        'subscription_expiring': '⏰',
        'referral_active': '🎁',
    };
    return icons[type] || '📬';
};

// Título según tipo
const getNotificationTitle = (notification) => {
    const data = notification.data || {};
    const types = {
        'new_message': `Mensaje de ${data.sender_name || 'Usuario'}`,
        'coach_registered': 'Nuevo Coach Registrado',
        'coach_approved': '¡Cuenta Aprobada!',
        'invoice_generated': `Factura ${data.invoice_number || ''}`,
        'payment_problem': 'Problema con el Pago',
        'payment_reminder': 'Renovación Próxima',
        'subscription_activated': '¡Suscripción Activada!',
        'subscription_expiring': 'Suscripción por Vencer',
        'referral_active': '¡Nuevo Referido!',
    };
    return types[data.type] || 'Notificación';
};

// Mensaje según tipo
const getNotificationMessage = (notification) => {
    const data = notification.data || {};
    
    if (data.message) return data.message;
    if (data.type === 'new_message' && data.message_preview) {
        return data.message_preview;
    }
    if (data.type === 'payment_reminder') {
        return `Tu suscripción vence en ${data.days_remaining} días`;
    }
    if (data.type === 'referral_active') {
        return `Has ganado $${data.bonus_amount} por referir a ${data.referred_user_name}`;
    }
    
    return 'Tienes una nueva notificación';
};

onMounted(() => {
    fetchNotifications();
    
    // Actualizar cada 30 segundos
    const interval = setInterval(fetchNotifications, 30000);
    
    // Cleanup
    return () => clearInterval(interval);
});
</script>

<template>
    <Menu as="div" class="relative">
        <MenuButton class="relative p-2 text-gray-400 hover:text-gray-500 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2">
            <span class="sr-only">Ver notificaciones</span>
            <BellAlertIcon v-if="unreadCount > 0" class="h-6 w-6 text-indigo-600 animate-pulse" />
            <BellIcon v-else class="h-6 w-6" />
            
            <!-- Badge de contador -->
            <span 
                v-if="unreadCount > 0" 
                class="absolute top-0 right-0 inline-flex items-center justify-center px-2 py-1 text-xs font-bold leading-none text-white transform translate-x-1/2 -translate-y-1/2 bg-red-600 rounded-full"
            >
                {{ unreadCount > 99 ? '99+' : unreadCount }}
            </span>
        </MenuButton>

        <transition
            enter-active-class="transition ease-out duration-100"
            enter-from-class="transform opacity-0 scale-95"
            enter-to-class="transform opacity-100 scale-100"
            leave-active-class="transition ease-in duration-75"
            leave-from-class="transform opacity-100 scale-100"
            leave-to-class="transform opacity-0 scale-95"
        >
            <MenuItems class="absolute right-0 z-10 mt-2 w-96 origin-top-right rounded-md bg-white shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none">
                <!-- Header -->
                <div class="px-4 py-3 border-b border-gray-200 flex items-center justify-between">
                    <h3 class="text-sm font-semibold text-gray-900">Notificaciones</h3>
                    <button 
                        v-if="unreadCount > 0"
                        @click="markAllAsRead"
                        class="text-xs text-indigo-600 hover:text-indigo-700"
                    >
                        Marcar todas como leídas
                    </button>
                </div>

                <!-- Lista de notificaciones -->
                <div class="max-h-96 overflow-y-auto">
                    <MenuItem 
                        v-for="notification in notifications.slice(0, 10)" 
                        :key="notification.id"
                        v-slot="{ active }"
                    >
                        <button
                            @click="handleNotificationClick(notification)"
                            :class="[
                                active ? 'bg-gray-50' : '',
                                !notification.read_at ? 'bg-indigo-50' : '',
                                'w-full px-4 py-3 text-left hover:bg-gray-50 transition-colors border-b border-gray-100'
                            ]"
                        >
                            <div class="flex items-start space-x-3">
                                <!-- Icono -->
                                <span class="text-2xl flex-shrink-0">
                                    {{ getNotificationIcon(notification.data?.type) }}
                                </span>
                                
                                <!-- Contenido -->
                                <div class="flex-1 min-w-0">
                                    <p class="text-sm font-medium text-gray-900">
                                        {{ getNotificationTitle(notification) }}
                                    </p>
                                    <p class="text-sm text-gray-600 line-clamp-2 mt-1">
                                        {{ getNotificationMessage(notification) }}
                                    </p>
                                    <p class="text-xs text-gray-400 mt-1">
                                        {{ timeAgo(notification.created_at) }}
                                    </p>
                                </div>
                                
                                <!-- Indicador de no leída -->
                                <div v-if="!notification.read_at" class="flex-shrink-0">
                                    <span class="inline-block h-2 w-2 rounded-full bg-indigo-600"></span>
                                </div>
                            </div>
                        </button>
                    </MenuItem>

                    <!-- Estado vacío -->
                    <div v-if="notifications.length === 0" class="px-4 py-8 text-center">
                        <BellIcon class="mx-auto h-12 w-12 text-gray-400" />
                        <p class="mt-2 text-sm text-gray-500">No tienes notificaciones</p>
                    </div>
                </div>

                <!-- Footer -->
                <div v-if="notifications.length > 0" class="px-4 py-3 border-t border-gray-200">
                    <a 
                        :href="route('notifications.index')"
                        class="text-sm text-indigo-600 hover:text-indigo-700 font-medium"
                    >
                        Ver todas las notificaciones →
                    </a>
                </div>
            </MenuItems>
        </transition>
    </Menu>
</template>
