// Copyright 1999-2020. Plesk International GmbH. All rights reserved.
import React, { useContext, useState, useRef, cloneElement, isValidElement } from 'react';
import { safeInvoke } from '../utils';
import ListOperationContext from './ListOperationContext';
import Popover from '../Popover';
import Translate from '../Translate';
import Button from '../Button';
import Media from '../Media';
import Icon from '../Icon';
import Text from '../Text';
import Paragraph from '../Paragraph';

const toBold = value => value === undefined ? undefined : /*#__PURE__*/React.createElement(Text, {
  bold: true
}, value);

const getDefaultText = key => {
  let fallback;

  switch (key) {
    case 'cancelButton':
      fallback = 'Cancel';
      break;

    default:
      throw new Error('Unknown key');
  }

  const content = "ListOperation.".concat(key);
  return /*#__PURE__*/React.createElement(Translate, {
    content: content,
    fallback: fallback
  });
};
/**
 * `ListOperation` component is used in [Toolbar](#!/Toolbar) for performing
 * operations on multiple objects in [List](#!/List).
 * @since 2.4.0
 */


const ListOperation = ({
  critical = false,
  noSelectionText,
  confirmationText,
  actionButtonText,
  cancelButtonText,
  children,
  ...props
}) => {
  const {
    selectedRows,
    selectedRowTitle
  } = useContext(ListOperationContext);
  const [settings, setSettings] = useState();
  const targetRef = useRef();

  if (! /*#__PURE__*/isValidElement(children)) {
    throw new Error('The "children" property must be an element.');
  }

  const toText = prop => {
    if (typeof prop === 'function') {
      return prop({
        selectedRows: toBold(selectedRows),
        selectedRowTitle: toBold(selectedRowTitle)
      });
    }

    return prop;
  };

  const handleClick = e => {
    targetRef.current = e.currentTarget;

    switch (true) {
      case selectedRows && critical:
        setSettings({
          message: toText(confirmationText),
          actionButtonText: toText(actionButtonText),
          actionButtonIntent: 'danger',
          cancelButtonText: toText(cancelButtonText) || getDefaultText('cancelButton')
        });
        break;

      case !selectedRows && !critical:
        setSettings({
          message: toText(noSelectionText),
          actionButtonText: toText(actionButtonText),
          actionButtonIntent: 'primary',
          cancelButtonText: toText(cancelButtonText) || getDefaultText('cancelButton')
        });
        break;

      case !selectedRows && critical:
        setSettings({
          message: toText(noSelectionText),
          icon: /*#__PURE__*/React.createElement(Icon, {
            intent: "info",
            name: "info-circle-filled"
          })
        });
        break;

      case selectedRows && !critical:
        safeInvoke(children.props.onClick, e);
        break;
    }
  };

  const handleCancel = () => {
    setSettings(null);
  };

  const handleAction = e => {
    setSettings(null);
    safeInvoke(children.props.onClick, e);
  };

  const target = /*#__PURE__*/cloneElement(children, { ...props,
    onClick: handleClick
  });
  return /*#__PURE__*/React.createElement(Popover, {
    visible: !!settings,
    target: target,
    targetRef: targetRef,
    placement: "top",
    onClose: handleCancel
  }, settings && /*#__PURE__*/React.createElement(Media, {
    image: settings.icon
  }, /*#__PURE__*/React.createElement(Paragraph, null, settings.message), settings.actionButtonText && /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(Button, {
    onClick: handleAction,
    intent: settings.actionButtonIntent
  }, settings.actionButtonText), " ", /*#__PURE__*/React.createElement(Button, {
    ghost: true,
    onClick: handleCancel
  }, settings.cancelButtonText))));
};

export default ListOperation;