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

const props = defineProps({
    ajustador: Object,
});

const notifications = ref([]);
const unreadCount = ref(0);
const showDropdown = ref(false);
const loading = ref(false);
let pollInterval = null;

const fetchNotifications = async () => {
    try {
        const response = await fetch('/ajustador/api/notifications', {
            headers: {
                'Accept': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            }
        });
        if (response.status === 401 || response.status === 403) {
            return;
        }
        const data = await response.json();
        notifications.value = data.notifications;
        unreadCount.value = data.unread_count;
    } catch (e) {
        console.error('Error fetching notifications:', e);
    }
};

const getCsrfToken = () => {
    const match = document.cookie.match(/(?:^|;\s*)XSRF-TOKEN=([^;]*)/);
    return match ? decodeURIComponent(match[1]) : '';
};

const markAsRead = async (notification) => {
    try {
        const res = await fetch(`/ajustador/api/notifications/${notification.id}/read`, {
            method: 'POST',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'X-XSRF-TOKEN': getCsrfToken(),
                'Accept': 'application/json',
            },
        });
        if (!res.ok) return;
        notification.leida = true;
        unreadCount.value = Math.max(0, unreadCount.value - 1);
    } catch (e) {
        console.error('Error marking notification as read:', e);
    }
};

const markAllAsRead = async () => {
    try {
        const res = await fetch('/ajustador/api/notifications/read-all', {
            method: 'POST',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'X-XSRF-TOKEN': getCsrfToken(),
                'Accept': 'application/json',
            },
        });
        if (!res.ok) return;
        notifications.value.forEach(n => n.leida = true);
        unreadCount.value = 0;
    } catch (e) {
        console.error('Error marking all as read:', e);
    }
};

const goToCase = (notification) => {
    markAsRead(notification);
    router.visit(route('ajustador.casos.show', notification.caso_id));
    showDropdown.value = false;
};

const toggleDropdown = () => {
    showDropdown.value = !showDropdown.value;
    if (showDropdown.value && notifications.value.length === 0) {
        fetchNotifications();
    }
};

const closeDropdown = (e) => {
    if (!e.target.closest('.notification-dropdown')) {
        showDropdown.value = false;
    }
};

onMounted(() => {
    fetchNotifications();
    pollInterval = setInterval(fetchNotifications, 30000);
    document.addEventListener('click', closeDropdown);
});

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

const timeAgo = (date) => {
    const now = new Date();
    const notificationDate = new Date(date);
    const diffMs = now - notificationDate;
    const diffMins = Math.floor(diffMs / 60000);
    const diffHours = Math.floor(diffMs / 3600000);
    const diffDays = Math.floor(diffMs / 86400000);

    if (diffMins < 1) return 'Ahora';
    if (diffMins < 60) return `Hace ${diffMins} min`;
    if (diffHours < 24) return `Hace ${diffHours}h`;
    return `Hace ${diffDays}d`;
};
</script>

<template>
    <div class="relative notification-dropdown">
        <button @click="toggleDropdown" class="relative p-2 text-slate-500 hover:text-blue-600 hover:bg-slate-100 rounded-full transition-colors">
            <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"></path>
            </svg>
            <span v-if="unreadCount > 0" class="absolute -top-1 -right-1 bg-red-500 text-white text-xs font-bold rounded-full w-5 h-5 flex items-center justify-center animate-pulse">
                {{ unreadCount > 9 ? '9+' : unreadCount }}
            </span>
        </button>

        <div v-if="showDropdown" class="absolute right-0 mt-2 w-80 bg-white rounded-xl shadow-2xl border border-slate-200 z-50 max-h-96 overflow-hidden">
            <div class="p-4 border-b border-slate-100 bg-gradient-to-r from-blue-50 to-slate-50">
                <div class="flex items-center justify-between">
                    <h3 class="font-bold text-slate-800">Notificaciones</h3>
                    <button v-if="unreadCount > 0" @click="markAllAsRead" class="text-xs text-blue-600 hover:text-blue-700 font-medium">
                        Marcar todas como leídas
                    </button>
                </div>
            </div>

            <div class="overflow-y-auto max-h-80">
                <div v-if="notifications.length === 0" class="p-8 text-center text-slate-400">
                    <svg class="w-12 h-12 mx-auto mb-3 opacity-50" 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"></path>
                    </svg>
                    <p class="text-sm">No tienes notificaciones</p>
                </div>

                <div
                    v-for="notification in notifications"
                    :key="notification.id"
                    @click="goToCase(notification)"
                    class="p-4 border-b border-slate-50 hover:bg-slate-50 cursor-pointer transition-colors"
                    :class="{ 'bg-blue-50/50': !notification.leida }"
                >
                    <div class="flex items-start gap-3">
                        <div class="w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0" :class="notification.leida ? 'bg-slate-100 text-slate-400' : 'bg-blue-100 text-blue-600'">
                            <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="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                            </svg>
                        </div>
                        <div class="flex-1 min-w-0">
                            <p class="text-sm text-slate-700 font-medium truncate">{{ notification.mensaje }}</p>
                            <p class="text-xs text-slate-400 mt-1">{{ timeAgo(notification.created_at) }}</p>
                        </div>
                        <span v-if="!notification.leida" class="w-2 h-2 bg-blue-500 rounded-full flex-shrink-0 mt-2"></span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
