"use client"; import { useState, useEffect } from "react"; import { Bell, Check } from "lucide-react"; import { Button } from "@/components/ui/button"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu"; import { Badge } from "@/components/ui/badge"; import { notificationApi } from "@/lib/api/notifications"; import { Notification } from "@/types/notification"; import { formatDistanceToNow } from "date-fns"; import Link from "next/link"; import { useRouter } from "next/navigation"; export function NotificationsDropdown() { const router = useRouter(); const [notifications, setNotifications] = useState([]); const [unreadCount, setUnreadCount] = useState(0); const [isOpen, setIsOpen] = useState(false); useEffect(() => { // Fetch notifications const fetchNotifications = async () => { try { const data = await notificationApi.getUnread(); setNotifications(data.items); setUnreadCount(data.unreadCount); } catch (error) { console.error("Failed to fetch notifications", error); } }; fetchNotifications(); }, []); const handleMarkAsRead = async (id: number, e: React.MouseEvent) => { e.stopPropagation(); await notificationApi.markAsRead(id); setNotifications((prev) => prev.map((n) => (n.notification_id === id ? { ...n, is_read: true } : n)) ); setUnreadCount((prev) => Math.max(0, prev - 1)); }; const handleNotificationClick = async (notification: Notification) => { if (!notification.is_read) { await notificationApi.markAsRead(notification.notification_id); setUnreadCount((prev) => Math.max(0, prev - 1)); } setIsOpen(false); if (notification.link) { router.push(notification.link); } }; return ( Notifications {unreadCount > 0 && ( {unreadCount} unread )} {notifications.length === 0 ? (
No notifications
) : (
{notifications.map((notification) => ( handleNotificationClick(notification)} >
{notification.title}
{!notification.is_read && ( )}
{notification.message}
{formatDistanceToNow(new Date(notification.created_at), { addSuffix: true, })}
))}
)} View All Notifications
); }