"use client";
import { ReactNode, useEffect, useState } from "react";
import style from "./Addable.module.css";
import { EVENT_TYPES, useEventHandlerStore } from "@store/EventHandler.Store";
import AddOutlinedIcon from "@mui/icons-material/AddOutlined";
import classNames from "classnames";

interface SaveableProps {
    children?: ReactNode;
    onClick?: () => void;
}

export default function Addable(props: SaveableProps): React.ReactElement {
    const eventHandler = useEventHandlerStore();
    const [buttonClassNames, setButtonClassNames] = useState(
        classNames(style.buttonSave, style.buttonSaveHidden)
    );

    useEffect(() => {
        if (eventHandler.eventType === EVENT_TYPES.NEED_ADD) {
            setButtonClassNames(classNames(style.buttonAdd, style.buttonAddVisible));
        } else {
            setButtonClassNames(classNames(style.buttonAdd, style.buttonAddHidden));
        }
    }, [eventHandler.eventType]);

    return (
        <>
            {props.children}
            <div
                className={buttonClassNames}
                onClick={() => {
                    if (props.onClick) {
                        props.onClick();
                        return;
                    }
                    eventHandler.setEventType(EVENT_TYPES.ADD);
                }}
            >
                <AddOutlinedIcon sx={{ fontSize: "32px" }} />
            </div>
        </>
    );
}
