import { useMemo } from "@wordpress/element";
import { useSelect, useDispatch } from "@wordpress/data";
import { store as noticesStore } from "@wordpress/notices";
import { Snackbar } from "@wordpress/components";

const getVariantFromStatus = (notice) => {
    if (typeof notice.status === "string" && notice.status.length > 0) {
        return notice.status; // success|error|warning|info
    }
    return "info";
};

/**
 * Renders snackbar notices from the WP notices store and adds a variant class
 * based on the notice status for custom styling (e.g. left-side icons).
 */
export default function Notices() {
    const notices = useSelect(
        (select) => select(noticesStore).getNotices(),
        [],
    );
    const { removeNotice } = useDispatch(noticesStore);

    const snackbarNotices = useMemo(
        () => notices.filter((notice) => notice.type === "snackbar"),
        [notices],
    );

    return (
        <div className='ekesto-snackbar-stack'>
            {snackbarNotices.map((notice) => {
                const variant = getVariantFromStatus(notice);

                return (
                    <Snackbar
                        key={notice.id}
                        icon={notice.icon}
                        onRemove={() => removeNotice(notice.id)}
                        className={`ekesto-snackbar ekesto-snackbar--${variant}`}
                    >
                        {notice.content}
                    </Snackbar>
                );
            })}
        </div>
    );
}
