import { useAtom } from 'jotai';
import { useResetAtom } from 'jotai/utils'
import { notificationQueueAtom, notificationHistoryAtom } from '../state/state.js';
import { showNotification } from '@mantine/notifications';
import { useEffect } from 'react';

function Notifications() {
    const [notificationQueue] = useAtom(notificationQueueAtom)
    const [,setNotificationHistory] = useAtom(notificationHistoryAtom)
    const resetNotifications = useResetAtom(notificationQueueAtom)


    useEffect(() => {
        if (notificationQueue.length > 0) {
            notificationQueue.forEach(notification => {
                // setting the full history so user can view it later
                setNotificationHistory((history) => [...history, notification])
                showNotification({
                    title: notification.title,
                    message: notification.message,
                    color: notification.color,
                    icon: notification.icon,
                    disallowClose: notification.disallowClose,
                })
            });
            resetNotifications()
        }
    }, [notificationQueue, resetNotifications, setNotificationHistory])
    
}

export default Notifications