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

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

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

    useEffect(() => {
        if (eventHandler.eventType === EVENT_TYPES.NEED_SAVE) {
            setButtonClassNames(classNames(style.buttonSave, style.buttonSaveVisible));
        } else {
            setButtonClassNames(classNames(style.buttonSave, style.buttonSaveHidden));
        }
    }, [eventHandler.eventType]);

    return (
        <>
            {props.children}
            <div
                className={buttonClassNames}
                onClick={() => {
                    if (props.onClick) {
                        props.onClick();
                        return;
                    }
                    eventHandler.setEventType(EVENT_TYPES.SAVE);
                }}
            >
                <SaveIcon />
            </div>
        </>
    );
}
