// Copyright 1999-2021. Plesk International GmbH. All rights reserved.
import React, { useState } from 'react';
import Button from '../Button';
import Dialog from '../Dialog';
import Paragraph from '../Paragraph';
import Translate from '../Translate';
import { safeInvoke } from '../utils';
import locale from './locale/en-US';

const useClosingConfirmation = ({
  onClose,
  closingConfirmation
}) => {
  const [isReady, setIsReady] = useState(false);
  const [isDialogVisible, setIsDialogVisible] = useState(false);

  const handleConfirm = () => {
    setIsDialogVisible(false);
    safeInvoke(onClose);
  };

  const handleCancel = () => {
    setIsDialogVisible(false);
  };

  let onCloseWithConfirmation;

  if (typeof onClose === 'function') {
    onCloseWithConfirmation = () => {
      if (closingConfirmation) {
        setIsReady(true);
        setIsDialogVisible(true);
      } else {
        onClose();
      }
    };
  }

  let closingConfirmationDialog = null;

  if (isReady) {
    closingConfirmationDialog = /*#__PURE__*/React.createElement(Dialog, {
      isOpen: isDialogVisible,
      size: "sm",
      onClose: handleCancel,
      buttons: [/*#__PURE__*/React.createElement(Button, {
        key: "cancel",
        intent: "primary",
        onClick: handleCancel
      }, /*#__PURE__*/React.createElement(Translate, {
        content: "ClosingConfirmation.cancel",
        fallback: locale.cancel
      })), /*#__PURE__*/React.createElement(Button, {
        key: "confirm",
        onClick: handleConfirm
      }, /*#__PURE__*/React.createElement(Translate, {
        content: "ClosingConfirmation.confirm",
        fallback: locale.confirm
      }))],
      cancelButton: false
    }, /*#__PURE__*/React.createElement(Paragraph, null, /*#__PURE__*/React.createElement(Translate, {
      content: "ClosingConfirmation.content",
      fallback: locale.content
    })));
  }

  return {
    onCloseWithConfirmation,
    closingConfirmationDialog
  };
};

export default useClosingConfirmation;