<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue';
import { Link, router } from '@inertiajs/vue3';

const props = defineProps({
    initialNotifications: {
        type: Array,
        default: () => []
    },
    initialUnreadCount: {
        type: Number,
        default: 0
    }
});

const isOpen = ref(false);
const notifications = ref(props.initialNotifications);
const unreadCount = ref(props.initialUnreadCount);
const isLoading = ref(false);

// Fetch notifications from API
const fetchNotifications = async () => {
    try {
        isLoading.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();
        // Filter out message notifications as they should only appear in the chat icon
        notifications.value = (data.notifications || []).filter(n => 
            n.type !== 'NewMessage' && 
            n.type !== 'NewMessageNotification' &&
            !n.type?.includes('NewMessage')
        );
        unreadCount.value = data.unreadCount || 0;
    } catch (error) {
    } finally {
        isLoading.value = false;
    }
};

// Mark single notification as read
const markAsRead = (notification) => {
    if (!notification.read_at) {
        router.post(route('notifications.read', notification.id), {}, {
            preserveScroll: true,
            onSuccess: () => {
                notification.read_at = new Date().toISOString();
                unreadCount.value = Math.max(0, unreadCount.value - 1);
            }
        });
    }
};

// Handle notification click - mark as read and navigate
const handleNotificationClick = (notification) => {
    markAsRead(notification);
    
    // Navigate to the notification URL if it exists
    const url = notification.data?.url;
    if (url) {
        isOpen.value = false;
        // Use router.visit for internal links
        if (url.startsWith('/') || url.includes(window.location.origin)) {
            router.visit(url);
        } else {
            window.location.href = url;
        }
    }
};

// Mark all as read
const markAllAsRead = () => {
    router.post(route('notifications.read-all'), {}, {
        preserveScroll: true,
        onSuccess: () => {
            notifications.value.forEach(n => n.read_at = new Date().toISOString());
            unreadCount.value = 0;
        }
    });
};

// Get notification icon based on type
const getNotificationIcon = (type) => {
    const icons = {
        'SubscriptionActivated': {
            icon: 'M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z',
            color: 'text-green-500 bg-green-100 dark:bg-green-900/30'
        },
        'SubscriptionExpiringSoon': {
            icon: 'M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z',
            color: 'text-amber-500 bg-amber-100 dark:bg-amber-900/30'
        },
        'CoachApproved': {
            icon: 'M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z',
            color: 'text-indigo-500 bg-indigo-100 dark:bg-indigo-900/30'
        },
        'NewMessage': {
            icon: 'M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z',
            color: 'text-blue-500 bg-blue-100 dark:bg-blue-900/30'
        },
        'NewMessageNotification': {
            icon: 'M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z',
            color: 'text-blue-500 bg-blue-100 dark:bg-blue-900/30'
        },
        'NewClient': {
            icon: 'M18 9v3m0 0v3m0-3h3m-3 0h-3m-2-5a4 4 0 11-8 0 4 4 0 018 0zM3 20a6 6 0 0112 0v1H3v-1z',
            color: 'text-purple-500 bg-purple-100 dark:bg-purple-900/30'
        },
        'PaymentReceived': {
            icon: 'M17 9V7a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2m2 4h10a2 2 0 002-2v-6a2 2 0 00-2-2H9a2 2 0 00-2 2v6a2 2 0 002 2zm7-5a2 2 0 11-4 0 2 2 0 014 0z',
            color: 'text-emerald-500 bg-emerald-100 dark:bg-emerald-900/30'
        },
        'AdminPaymentReceived': {
            icon: 'M17 9V7a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2m2 4h10a2 2 0 002-2v-6a2 2 0 00-2-2H9a2 2 0 00-2 2v6a2 2 0 002 2zm7-5a2 2 0 11-4 0 2 2 0 014 0z',
            color: 'text-emerald-500 bg-emerald-100 dark:bg-emerald-900/30'
        },
        'NewCoachRegistered': {
            icon: 'M18 9v3m0 0v3m0-3h3m-3 0h-3m-2-5a4 4 0 11-8 0 4 4 0 018 0zM3 20a6 6 0 0112 0v1H3v-1z',
            color: 'text-indigo-500 bg-indigo-100 dark:bg-indigo-900/30'
        },
        'AdminCoachPlanPurchased': {
            icon: 'M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z',
            color: 'text-green-500 bg-green-100 dark:bg-green-900/30'
        },
        'InvoiceGenerated': {
            icon: 'M9 12h6m-6 4h6m2 5H7a2 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',
            color: 'text-blue-500 bg-blue-100 dark:bg-blue-900/30'
        },
        'InvoicePaid': {
            icon: 'M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z',
            color: 'text-green-500 bg-green-100 dark:bg-green-900/30'
        },
        'InvoiceOverdue': {
            icon: 'M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z',
            color: 'text-red-500 bg-red-100 dark:bg-red-900/30'
        },
        'AdminInvoiceOverdue': {
            icon: 'M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z',
            color: 'text-red-500 bg-red-100 dark:bg-red-900/30'
        },
        'ClientPortalActivated': {
            icon: 'M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11 17H9v2H7v2H4a1 1 0 01-1-1v-2.586a1 1 0 01.293-.707l5.964-5.964A6 6 0 1121 9z',
            color: 'text-purple-500 bg-purple-100 dark:bg-purple-900/30'
        },
        'AdminNewSupportMessage': {
            icon: 'M18.364 5.636l-3.536 3.536m0 5.656l3.536 3.536M9.172 9.172L5.636 5.636m3.536 9.192l-3.536 3.536M21 12a9 9 0 11-18 0 9 9 0 0118 0zm-5 0a4 4 0 11-8 0 4 4 0 018 0z',
            color: 'text-orange-500 bg-orange-100 dark:bg-orange-900/30'
        },
        // Diet & Routine Notifications
        'meal_plan_assigned': {
            icon: 'M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253',
            color: 'text-green-500 bg-green-100 dark:bg-green-900/30'
        },
        'meal_plan_updated': {
            icon: 'M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15',
            color: 'text-blue-500 bg-blue-100 dark:bg-blue-900/30'
        },
        'workout_assigned': {
            icon: 'M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z',
            color: 'text-orange-500 bg-orange-100 dark:bg-orange-900/30'
        },
        'workout_updated': {
            icon: 'M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15',
            color: 'text-blue-500 bg-blue-100 dark:bg-blue-900/30'
        },
        // Store Order Notifications
        'OrderConfirmed': {
            icon: 'M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z',
            color: 'text-green-500 bg-green-100 dark:bg-green-900/30'
        },
        'OrderPaid': {
            icon: 'M17 9V7a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2m2 4h10a2 2 0 002-2v-6a2 2 0 00-2-2H9a2 2 0 00-2 2v6a2 2 0 002 2zm7-5a2 2 0 11-4 0 2 2 0 014 0z',
            color: 'text-emerald-500 bg-emerald-100 dark:bg-emerald-900/30'
        },
        'OrderShipped': {
            icon: 'M13 16V6a1 1 0 00-1-1H4a1 1 0 00-1 1v10a1 1 0 001 1h1m8-1a1 1 0 01-1 1H9m4-1V8a1 1 0 011-1h2.586a1 1 0 01.707.293l3.414 3.414a1 1 0 01.293.707V16a1 1 0 01-1 1h-1m-6-1a1 1 0 001 1h1M5 17a2 2 0 104 0m-4 0a2 2 0 114 0m6 0a2 2 0 104 0m-4 0a2 2 0 114 0',
            color: 'text-blue-500 bg-blue-100 dark:bg-blue-900/30'
        },
        'OrderDelivered': {
            icon: 'M5 13l4 4L19 7',
            color: 'text-green-500 bg-green-100 dark:bg-green-900/30'
        },
        'OrderCancelled': {
            icon: 'M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z',
            color: 'text-red-500 bg-red-100 dark:bg-red-900/30'
        },
        'OrderRefunded': {
            icon: 'M3 10h10a8 8 0 018 8v2M3 10l6 6m-6-6l6-6',
            color: 'text-amber-500 bg-amber-100 dark:bg-amber-900/30'
        },
        'OrderPaymentFailed': {
            icon: 'M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z',
            color: 'text-red-500 bg-red-100 dark:bg-red-900/30'
        },
        'OrderStatusChanged': {
            icon: 'M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15',
            color: 'text-indigo-500 bg-indigo-100 dark:bg-indigo-900/30'
        },
        // Admin Store Notifications
        'AdminNewStoreOrder': {
            icon: 'M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z',
            color: 'text-purple-500 bg-purple-100 dark:bg-purple-900/30'
        },
        'AdminStorePaymentReceived': {
            icon: 'M17 9V7a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2m2 4h10a2 2 0 002-2v-6a2 2 0 00-2-2H9a2 2 0 00-2 2v6a2 2 0 002 2zm7-5a2 2 0 11-4 0 2 2 0 014 0z',
            color: 'text-emerald-500 bg-emerald-100 dark:bg-emerald-900/30'
        },
        'AdminOrderShipped': {
            icon: 'M13 16V6a1 1 0 00-1-1H4a1 1 0 00-1 1v10a1 1 0 001 1h1m8-1a1 1 0 01-1 1H9m4-1V8a1 1 0 011-1h2.586a1 1 0 01.707.293l3.414 3.414a1 1 0 01.293.707V16a1 1 0 01-1 1h-1m-6-1a1 1 0 001 1h1M5 17a2 2 0 104 0m-4 0a2 2 0 114 0m6 0a2 2 0 104 0m-4 0a2 2 0 114 0',
            color: 'text-blue-500 bg-blue-100 dark:bg-blue-900/30'
        },
        'AdminOrderDelivered': {
            icon: 'M5 13l4 4L19 7',
            color: 'text-green-500 bg-green-100 dark:bg-green-900/30'
        },
        'AdminOrderPaymentFailed': {
            icon: 'M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z',
            color: 'text-red-500 bg-red-100 dark:bg-red-900/30'
        },
        'default': {
            icon: 'M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9',
            color: 'text-gray-500 bg-gray-100 dark:bg-gray-700'
        }
    };
    return icons[type] || icons.default;
};

// Get notification message
const getNotificationMessage = (notification) => {
    return notification.data?.message || notification.data?.title || 'Nueva notificación';
};

// Close dropdown when clicking outside
const handleClickOutside = (event) => {
    const dropdown = document.getElementById('notification-dropdown');
    if (dropdown && !dropdown.contains(event.target)) {
        isOpen.value = false;
    }
};

// Periodic refresh
let refreshInterval;

onMounted(() => {
    document.addEventListener('click', handleClickOutside);
    fetchNotifications();
    
    // Refresh every 30 seconds
    refreshInterval = setInterval(fetchNotifications, 30000);
});

onUnmounted(() => {
    document.removeEventListener('click', handleClickOutside);
    if (refreshInterval) {
        clearInterval(refreshInterval);
    }
});

const toggleDropdown = (event) => {
    event.stopPropagation();
    isOpen.value = !isOpen.value;
    if (isOpen.value && notifications.value.length === 0) {
        fetchNotifications();
    }
};
</script>

<template>
    <div id="notification-dropdown" class="relative">
        <!-- Notification bell button -->
        <button 
            @click="toggleDropdown"
            class="p-2 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg relative transition-colors"
            :class="{ 'bg-gray-100 dark:bg-gray-700': isOpen }"
        >
            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9" />
            </svg>
            <!-- Unread badge -->
            <span 
                v-if="unreadCount > 0"
                class="absolute -top-0.5 -right-0.5 flex items-center justify-center min-w-[18px] h-[18px] px-1 text-xs font-bold text-white bg-red-500 rounded-full animate-pulse"
            >
                {{ unreadCount > 99 ? '99+' : unreadCount }}
            </span>
        </button>

        <!-- Dropdown panel -->
        <Transition
            enter-active-class="transition ease-out duration-200"
            enter-from-class="transform opacity-0 scale-95"
            enter-to-class="transform opacity-100 scale-100"
            leave-active-class="transition ease-in duration-150"
            leave-from-class="transform opacity-100 scale-100"
            leave-to-class="transform opacity-0 scale-95"
        >
            <div 
                v-if="isOpen"
                class="absolute right-0 mt-2 w-80 sm:w-96 bg-white dark:bg-gray-800 rounded-xl shadow-lg ring-1 ring-black ring-opacity-5 dark:ring-gray-700 overflow-hidden z-50"
            >
                <!-- Header -->
                <div class="px-4 py-3 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between">
                    <h3 class="text-sm font-semibold text-gray-900 dark:text-white">Notificaciones</h3>
                    <div class="flex items-center space-x-2">
                        <button 
                            v-if="unreadCount > 0"
                            @click="markAllAsRead"
                            class="text-xs text-indigo-600 dark:text-indigo-400 hover:text-indigo-800 dark:hover:text-indigo-300 font-medium"
                        >
                            Marcar todas como leídas
                        </button>
                    </div>
                </div>

                <!-- Notification list -->
                <div class="max-h-96 overflow-y-auto">
                    <!-- Loading state -->
                    <div v-if="isLoading && notifications.length === 0" class="p-8 text-center">
                        <div class="animate-spin w-8 h-8 border-4 border-indigo-500 border-t-transparent rounded-full mx-auto"></div>
                        <p class="mt-2 text-sm text-gray-500 dark:text-gray-400">Cargando...</p>
                    </div>

                    <!-- Empty state -->
                    <div v-else-if="notifications.length === 0" class="p-8 text-center">
                        <svg class="w-12 h-12 mx-auto text-gray-300 dark:text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9" />
                        </svg>
                        <p class="mt-3 text-sm font-medium text-gray-900 dark:text-white">No hay notificaciones</p>
                        <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">Te avisaremos cuando haya algo nuevo</p>
                    </div>

                    <!-- Notification items -->
                    <div v-else>
                        <button
                            v-for="notification in notifications"
                            :key="notification.id"
                            @click="handleNotificationClick(notification)"
                            class="w-full px-4 py-3 flex items-start space-x-3 hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors text-left cursor-pointer"
                            :class="{ 'bg-indigo-50/50 dark:bg-indigo-900/20': !notification.read_at }"
                        >
                            <!-- Icon -->
                            <div 
                                :class="[
                                    'flex-shrink-0 w-10 h-10 rounded-full flex items-center justify-center',
                                    getNotificationIcon(notification.type).color
                                ]"
                            >
                                <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="getNotificationIcon(notification.type).icon" />
                                </svg>
                            </div>

                            <!-- Content -->
                            <div class="flex-1 min-w-0">
                                <p 
                                    class="text-sm text-gray-900 dark:text-white"
                                    :class="{ 'font-semibold': !notification.read_at }"
                                >
                                    {{ getNotificationMessage(notification) }}
                                </p>
                                <p class="mt-0.5 text-xs text-gray-500 dark:text-gray-400">
                                    {{ notification.human_time }}
                                </p>
                            </div>

                            <!-- Unread indicator -->
                            <div v-if="!notification.read_at" class="flex-shrink-0">
                                <span class="w-2 h-2 bg-indigo-500 rounded-full block"></span>
                            </div>
                        </button>
                    </div>
                </div>

                <!-- Footer -->
                <div class="px-4 py-3 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-700/50">
                    <Link 
                        :href="route('notifications.index')"
                        class="block text-center text-sm font-medium text-indigo-600 dark:text-indigo-400 hover:text-indigo-800 dark:hover:text-indigo-300"
                    >
                        Ver todas las notificaciones
                    </Link>
                </div>
            </div>
        </Transition>
    </div>
</template>
