import {
    createRef,
    forwardRef,
    useEffect,
    useImperativeHandle,
    useState,
} from 'react';

import { Notification } from 'konsta/react';

type ToastRootRefType = {
    show: (message: string | React.ReactNode) => void;
}


export const toastRootRef = createRef<ToastRootRefType>();


export const toast = (message: string | React.ReactNode) => {
    toastRootRef.current?.show(message);
}

const ToastRoot = forwardRef<ToastRootRefType, {}>((_, ref) => {


    const [message, setMessage] = useState<string | React.ReactNode | null>(null);

    useImperativeHandle(ref, () => ({
        show: (message) => {
            setMessage(message);

        },

    }));

    useEffect(() => {
        if (message) {
            const timer = setTimeout(() => {
                setMessage(null);
            }, 3000);
            return () => clearTimeout(timer);
        }
    }, [message]);



    return <Notification
        opened={!!message}
        onClick={() => {
            setMessage(null);
        }}
        text={message}
        button
    />

});

export default ToastRoot;