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

const props = defineProps({
    showToasts: {
        type: Boolean,
        default: true,
    },
});

const emit = defineEmits(['notification']);

const notifications = ref([]);
const isConnected = ref(false);

// Get current user
const page = usePage();
const user = page.props.auth?.user;

// Subscribe to user's private channel
const setupEcho = () => {
    if (!user || !window.Echo) {
        return;
    }

    const channel = window.Echo.private(`App.Models.User.${user.id}`);

    channel
        .listen('.notification', (event) => {
            
            // Add to notifications list
            notifications.value.unshift({
                id: event.id || Date.now(),
                ...event,
            });

            // Emit event for parent components
            emit('notification', event);

            // Show toast if enabled
            if (props.showToasts) {
                showToast(event);
            }

            // Auto-remove after 10 seconds
            setTimeout(() => {
                removeNotification(event.id);
            }, 10000);
        })
        .subscribed(() => {
            isConnected.value = true;
        })
        .error((error) => {
            isConnected.value = false;
        });
};

const showToast = (notification) => {
    // You can integrate with a toast library here
    // For now, we'll use the native notification API as fallback
    if ('Notification' in window && Notification.permission === 'granted') {
        new Notification(notification.title, {
            body: notification.message,
            icon: '/icons/icon-192x192.png',
            tag: notification.id,
        });
    }
};

const removeNotification = (id) => {
    const index = notifications.value.findIndex(n => n.id === id);
    if (index > -1) {
        notifications.value.splice(index, 1);
    }
};

const clearAll = () => {
    notifications.value = [];
};

onMounted(() => {
    setupEcho();
});

onUnmounted(() => {
    if (user && window.Echo) {
        window.Echo.leave(`App.Models.User.${user.id}`);
    }
});
</script>

<template>
    <!-- Notification Toast Container -->
    <div class="fixed top-4 right-4 z-50 space-y-2 max-w-sm w-full" v-if="notifications.length > 0">
        <TransitionGroup name="notification">
            <div
                v-for="notification in notifications.slice(0, 5)"
                :key="notification.id"
                class="bg-white dark:bg-gray-800 rounded-lg shadow-lg border border-gray-200 dark:border-gray-700 overflow-hidden"
            >
                <div class="p-4">
                    <div class="flex items-start">
                        <!-- Icon based on type -->
                        <div class="flex-shrink-0">
                            <div 
                                class="w-8 h-8 rounded-full flex items-center justify-center"
                                :class="{
                                    'bg-blue-100 text-blue-600': notification.type === 'info',
                                    'bg-green-100 text-green-600': notification.type === 'success',
                                    'bg-yellow-100 text-yellow-600': notification.type === 'warning',
                                    'bg-red-100 text-red-600': notification.type === 'error',
                                    'bg-purple-100 text-purple-600': !notification.type,
                                }"
                            >
                                <svg v-if="notification.type === 'success'" 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="M5 13l4 4L19 7" />
                                </svg>
                                <svg v-else-if="notification.type === 'error'" 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="M6 18L18 6M6 6l12 12" />
                                </svg>
                                <svg v-else-if="notification.type === 'warning'" 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="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" />
                                </svg>
                                <svg v-else 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 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>
                            </div>
                        </div>
                        
                        <!-- Content -->
                        <div class="ml-3 flex-1">
                            <p class="text-sm font-medium text-gray-900 dark:text-white">
                                {{ notification.title }}
                            </p>
                            <p class="mt-1 text-sm text-gray-500 dark:text-gray-400">
                                {{ notification.message }}
                            </p>
                            <a
                                v-if="notification.link"
                                :href="notification.link"
                                class="mt-2 text-sm font-medium text-blue-600 hover:text-blue-500 dark:text-blue-400"
                            >
                                Ver más →
                            </a>
                        </div>
                        
                        <!-- Close button -->
                        <button
                            @click="removeNotification(notification.id)"
                            class="flex-shrink-0 ml-2 text-gray-400 hover:text-gray-500"
                        >
                            <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="M6 18L18 6M6 6l12 12" />
                            </svg>
                        </button>
                    </div>
                </div>
            </div>
        </TransitionGroup>
        
        <!-- Clear all button -->
        <button
            v-if="notifications.length > 1"
            @click="clearAll"
            class="w-full text-center text-sm text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
        >
            Limpiar todas
        </button>
    </div>
    
    <!-- Connection status indicator (optional, for debugging) -->
    <slot name="status" :connected="isConnected" />
</template>

<style scoped>
.notification-enter-active {
    transition: all 0.3s ease-out;
}

.notification-leave-active {
    transition: all 0.2s ease-in;
}

.notification-enter-from {
    opacity: 0;
    transform: translateX(100%);
}

.notification-leave-to {
    opacity: 0;
    transform: translateX(100%);
}
</style>
