/**
 * External dependencies
 */

/**
 * WordPress dependencies
 */
import { __ } from "@wordpress/i18n";
import { Button, Notice, Spinner } from "@wordpress/components";
import { useState } from "@wordpress/element";
import { useDispatch } from "@wordpress/data";
import { store as coreStore } from "@wordpress/core-data";

export const SaveActions = ({ onSave }) => {
  const [isLoading, setIsLoading] = useState(false);

  const handleSave = (e) => {
    e.preventDefault();
    setIsLoading(true);
    onSave().finally(() => {
      setIsLoading(false);
    });
  };

  return (
    <>
      <Button variant="primary" onClick={handleSave}>
        {__("Update Settings")}
      </Button>
      {isLoading && <Spinner />}
    </>
  );
};

export const useHandleSave = (Messages) => {
  const { saveEditedEntityRecord } = useDispatch(coreStore);
  const [messageData, setMessageData] = useState({
    type: "success",
    message: "",
  });

  const handleSave = () => {
    return saveEditedEntityRecord("root", "site")
      .then(() => {
        setMessageData({
          type: "success",
          message: Messages.Success,
        });
      })
      .catch((error) => {
        log(error, "error");
        setMessageData({
          type: "error",
          message: Messages.Error,
        });
      });
  };

  const MessageNotice = () =>
    messageData &&
    messageData?.message && (
      <Notice status={messageData?.type} isDismissible={false}>
        {messageData.message}
      </Notice>
    );

  return { handleSave, MessageNotice };
};
