import { ReactNode, useEffect, useRef } from 'react';

export interface NotificationItemProps {
    /** Content to render into the NotificationItem */
    children: ReactNode;
    /** Allow the notifications to be autoclosed */
    autoClose: boolean;
    /** Time till the notification is closed */
    delay: number;
    /** Called when to close the item */
    onClose: () => void;
}

export const NotificationItem = (props: NotificationItemProps): JSX.Element => {
    const { children, autoClose, delay, onClose } = props;

    // store the timer in a ref and autoclose after the delay
    const timer = useRef<ReturnType<typeof setTimeout> | null>(null);

    // start the timer on mount
    useEffect(() => {
        if (autoClose) {
            timer.current = setTimeout(() => {
                onClose();
            }, delay);
        }

        return () => {
            if (!timer.current) {
                return;
            }

            clearTimeout(timer.current);
        };
    }, [onClose, autoClose, delay]);
    return <>{children}</>;
};
