'use client' import { useState, useEffect, useCallback } from 'react' import { useRouter } from 'next/navigation' import { Button } from '@/components/ui/button' import { Badge } from '@/components/ui/badge' import { Bell, Check, X, Clock, AlertCircle, CheckCircle2, Circle, Share2, Bot, Trash2, Download, Pencil, Presentation } from 'lucide-react' import { Popover, PopoverContent, PopoverTrigger, } from '@/components/ui/popover' import { getPendingShareRequests, respondToShareRequest, getNotesWithReminders, toggleReminderDone } from '@/app/actions/notes' import { getUnreadNotifications, markNotificationRead, markAllNotificationsRead, type AppNotification } from '@/app/actions/notifications' import { toast } from 'sonner' import { useNoteRefreshOptional } from '@/context/NoteRefreshContext' import { cn } from '@/lib/utils' import { useLanguage } from '@/lib/i18n' import { formatDistanceToNow } from 'date-fns' interface ShareRequest { id: string status: string permission: string createdAt: Date note: { id: string title: string | null content: string color: string createdAt: Date } sharer: { id: string name: string | null email: string image: string | null } } interface ReminderNote { id: string title: string | null content: string reminder: Date | string | null isReminderDone: boolean } export function NotificationPanel() { const { triggerRefresh } = useNoteRefreshOptional() const { t } = useLanguage() const router = useRouter() const [requests, setRequests] = useState([]) const [reminders, setReminders] = useState([]) const [appNotifications, setAppNotifications] = useState([]) const [isLoading, setIsLoading] = useState(false) const [open, setOpen] = useState(false) const loadData = useCallback(async () => { try { const [shareData, reminderData, notifData] = await Promise.all([ getPendingShareRequests(), getNotesWithReminders(), getUnreadNotifications(), ]) setRequests(shareData as any) setReminders((reminderData as any) || []) setAppNotifications(notifData || []) } catch (error: any) { console.error('Failed to load notifications:', error) } }, []) useEffect(() => { loadData() const interval = setInterval(loadData, 30000) const onFocus = () => loadData() window.addEventListener('focus', onFocus) return () => { clearInterval(interval) window.removeEventListener('focus', onFocus) } }, [loadData]) const now = new Date() const activeReminders = reminders.filter(r => !r.isReminderDone && r.reminder) const overdueReminders = activeReminders.filter(r => new Date(r.reminder!) < now) const upcomingReminders = activeReminders.filter(r => new Date(r.reminder!) >= now) const pendingCount = requests.length + overdueReminders.length + appNotifications.length const handleAccept = async (shareId: string) => { try { await respondToShareRequest(shareId, 'accept') setRequests(prev => prev.filter(r => r.id !== shareId)) toast.success(t('notification.accepted'), { description: t('collaboration.nowHasAccess', { name: 'Note' }), duration: 3000, }) triggerRefresh() setOpen(false) } catch (error: any) { console.error('[NOTIFICATION] Error:', error) toast.error(error.message || t('general.error')) } } const handleDecline = async (shareId: string) => { try { await respondToShareRequest(shareId, 'decline') setRequests(prev => prev.filter(r => r.id !== shareId)) toast.info(t('notification.declined')) if (requests.length <= 1) setOpen(false) } catch (error: any) { console.error('[NOTIFICATION] Error:', error) toast.error(error.message || t('general.error')) } } const handleToggleReminder = async (noteId: string, done: boolean) => { try { await toggleReminderDone(noteId, done) setReminders(prev => prev.map(r => r.id === noteId ? { ...r, isReminderDone: done } : r)) triggerRefresh() } catch { toast.error(t('general.error')) } } const handleMarkNotifRead = async (notifId: string) => { await markNotificationRead(notifId) setAppNotifications(prev => prev.filter(n => n.id !== notifId)) } const handleMarkAllRead = async () => { await markAllNotificationsRead() setAppNotifications([]) } const hasContent = requests.length > 0 || activeReminders.length > 0 || appNotifications.length > 0 return (
{t('notification.notifications')}
{appNotifications.length > 0 && ( )} {pendingCount > 0 && ( {pendingCount} )}
{isLoading ? (
) : !hasContent ? (

{t('notification.noNotifications') || 'No new notifications'}

) : (
{/* App notifications (agents, system) */} {appNotifications.map((notif) => { const isSlides = notif.type === 'agent_slides_ready' const isCanvas = notif.type === 'agent_canvas_ready' const canvasId = notif.relatedId return (
{ if (notif.actionUrl) { handleMarkNotifRead(notif.id) setOpen(false) router.push(notif.actionUrl) } }} >
{isSlides ? ( ) : isCanvas ? ( ) : notif.type.startsWith('agent') ? ( ) : ( )}
{notif.type === 'agent_slides_ready' && (t('notification.slidesReady') || 'Slides Ready')} {notif.type === 'agent_canvas_ready' && (t('notification.canvasReady') || 'Diagram Ready')} {notif.type === 'agent_success' && (t('notification.agentSuccess') || 'Agent completed')} {notif.type === 'agent_failure' && (t('notification.agentFailed') || 'Agent failed')} {notif.type === 'system' && 'System'}

{notif.title}

{notif.message && (

{notif.message}

)}
{formatDistanceToNow(new Date(notif.createdAt), { addSuffix: true })}
{isSlides && canvasId && (
)}
) })} {/* Overdue reminders */} {overdueReminders.map((note) => (
{t('reminders.overdue')}

{note.title || t('notification.untitled')}

{note.reminder && formatDistanceToNow(new Date(note.reminder), { addSuffix: true })}
))} {/* Upcoming reminders */} {upcomingReminders.slice(0, 5).map((note) => (

{note.title || t('notification.untitled')}

{note.reminder && new Date(note.reminder).toLocaleDateString(undefined, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })}
))} {/* Share requests */} {requests.map((request) => (
{(request.sharer.name || request.sharer.email)[0].toUpperCase()}

{request.sharer.name || request.sharer.email}

{t('notification.shared', { title: request.note.title || t('notification.untitled') })}

))}
)} {/* Footer link to reminders page */} {activeReminders.length > 0 && ( )} ) }