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

export type Message = {
    message: string;
    type: "error" | "success";
};

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

    return (
        <FlashContext.Provider
            value={(message: Message) => {
                setMessages((messages: Message[]) => [...messages, message]);
                setTimeout(() => {
                    setMessages((messages) => [...messages].splice(1));
                }, MESSAGE_FLASH_TIME);
            }}
        >
            <>
                {children}
                <div class="flash-container">
                    {messages.map((message) => {
                        const className = message.type === "error" ? "is-danger" : "is-success";
                        const icon =
                            message.type === "error" ? "fa-exclamation-circle" : "fa-check";

                        return (
                            <div class={`notification flash-message is-active ${className}`}>
                                <span class="icon">
                                    <i class={`far ${icon}`}></i>
                                </span>{" "}
                                <span class="error-message">{message.message}</span>
                            </div>
                        );
                    })}
                </div>
            </>
        </FlashContext.Provider>
    );
};
