import { FlashContext } from "./FlashContext";
import { useState } from "preact/hooks";
import { MESSAGE_FLASH_TIME } from "../../consts";

export const FlashProvider = ({ children }) => {
    const [messages, setMessages] = useState([] as string[]);

    return (
        <FlashContext.Provider
            value={(message: string) => {
                setMessages((messages: string[]) => [...messages, message]);
                setTimeout(() => {
                    setMessages((messages) => [...messages].splice(1));
                }, MESSAGE_FLASH_TIME);
            }}
        >
            <>
                {children}
                {messages.map((message) => (
                    <div class="notification is-danger flash-message is-active">
                        <span class="icon">
                            <i class="far fa-exclamation-circle"></i>
                        </span>{" "}
                        <span class="error-message">{message}</span>
                    </div>
                ))}
            </>
        </FlashContext.Provider>
    );
};
