import _extends from "@babel/runtime/helpers/extends";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
// Copyright 1999-2020. Plesk International GmbH. All rights reserved.

/* eslint-disable react/no-deprecated */
import React, { Component, Children, isValidElement, useContext } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import Measure from 'react-measure';
import { CLS_PREFIX } from '../../constants';
import { isClickable } from '../utils';
import InPlaceEdit from '../InPlaceEdit';
import Button from '../Button';
import VerticalContext, { VERTICAL_BREAKPOINT } from '../VerticalContext';
import FormContext from '../Form/FormContext';

const getErrorsForChildren = (form, children) => {
  let errors = {};
  Children.forEach(children, child => {
    if (! /*#__PURE__*/isValidElement(child)) {
      return;
    }

    if (child.props.name) {
      errors = { ...errors,
        ...form.getErrors(child.props.name)
      };
    }

    if (child.props.children) {
      errors = { ...errors,
        ...getErrorsForChildren(form, child.props.children)
      };
    }
  });
  return errors;
};

class Section extends Component {
  constructor(...args) {
    super(...args);

    _defineProperty(this, "state", {
      vertical: false
    });

    _defineProperty(this, "handleResize", ({
      bounds
    }) => {
      if (this.props.vertical !== undefined) {
        return;
      }

      this.setState({
        vertical: bounds.width < VERTICAL_BREAKPOINT
      });
    });

    _defineProperty(this, "handleCollapse", e => {
      if (isClickable(e)) {
        return;
      }

      this.setState(({
        collapsed
      }) => ({
        collapsed: !collapsed
      }), () => {
        if (this.props.onToggle) {
          this.props.onToggle(this.state.collapsed);
        }
      });
    });
  }

  static getDerivedStateFromProps(props, state) {
    const {
      collapsible,
      collapsed,
      form,
      children
    } = props;
    const {
      prevCollapsed,
      prevErrors
    } = state;
    const nextState = {};

    if (collapsed !== prevCollapsed) {
      nextState.collapsed = collapsed;
    }

    nextState.prevCollapsed = collapsed;

    if (collapsible && form) {
      const errors = getErrorsForChildren(form, children);

      if (JSON.stringify(errors) !== JSON.stringify(prevErrors) && Object.keys(errors).length > 0) {
        nextState.collapsed = false;
      }

      nextState.prevErrors = errors;
    }

    return nextState;
  }

  renderCollapseButton({
    baseClassName,
    collapsible
  }) {
    const {
      collapsed
    } = this.state;
    return collapsible && /*#__PURE__*/React.createElement(Button, {
      ghost: true,
      className: classNames(`${baseClassName}__control-button`, `${baseClassName}__control-button--collapse`),
      icon: {
        name: 'chevron-up',
        flipVertical: collapsed
      },
      onClick: this.handleCollapse
    });
  }

  renderCloseButton({
    baseClassName,
    onClose,
    buttons
  }) {
    return (onClose || buttons) && /*#__PURE__*/React.createElement("div", {
      className: `${baseClassName}__header-buttons`
    }, buttons, onClose && /*#__PURE__*/React.createElement(Button, {
      ghost: true,
      className: classNames(`${baseClassName}__control-button`, `${baseClassName}__control-button--close`),
      onClick: onClose,
      icon: "cross-mark"
    }));
  }

  renderTitle({
    baseClassName,
    title,
    onTitleChange
  }) {
    return title && /*#__PURE__*/React.createElement(InPlaceEdit, {
      className: `${baseClassName}__title`,
      value: title,
      onChange: onTitleChange,
      onClick: e => {
        var _e$target$closest$que;

        (_e$target$closest$que = e.target.closest(`.${baseClassName}__header`).querySelector(`.${baseClassName}__control-button`)) === null || _e$target$closest$que === void 0 ? void 0 : _e$target$closest$que.click();
      }
    });
  }

  renderContent({
    collapsible,
    children
  }) {
    const {
      collapsed
    } = this.state;

    if (collapsible && collapsed) {
      return null;
    }

    return children;
  }

  render() {
    const {
      baseClassName,
      className,
      intent,
      collapsible,
      title,
      collapsed,
      onTitleChange,
      onClose,
      onToggle,
      buttons,
      vertical: verticalProp,
      children,
      form,
      ...props
    } = this.props;
    const vertical = verticalProp === undefined ? this.state.vertical : verticalProp;
    return /*#__PURE__*/React.createElement(VerticalContext.Provider, {
      value: vertical
    }, /*#__PURE__*/React.createElement(Measure, {
      onResize: this.handleResize,
      bounds: true
    }, ({
      measureRef
    }) => /*#__PURE__*/React.createElement("div", _extends({
      ref: measureRef,
      className: classNames(baseClassName, {
        [`${baseClassName}--${intent}`]: intent,
        [`${baseClassName}--collapsible`]: collapsible,
        [`${baseClassName}--collapsed`]: this.state.collapsed,
        [`${baseClassName}--vertical`]: vertical
      }, className)
    }, props), title && /*#__PURE__*/React.createElement("div", {
      className: `${baseClassName}__header`
    }, this.renderCollapseButton({
      baseClassName,
      collapsible
    }), this.renderTitle({
      baseClassName,
      title,
      onTitleChange
    }), this.renderCloseButton({
      baseClassName,
      onClose,
      buttons
    })), this.renderContent({
      collapsible,
      children
    }))));
  }

}

const propTypes = {
  /**
   * Title of the section.
   * @since 0.0.54
   */
  title: PropTypes.node,

  /**
   * Visual intent color to apply to component.
   * @since 0.0.54
   */
  intent: PropTypes.oneOf(['danger', 'warning', 'success', 'inactive']),

  /**
   * Is section collapsible.
   * @since 0.0.54
   */
  collapsible: PropTypes.bool,

  /**
   * Is section collapsed now.
   * @since 0.0.54
   */
  collapsed: PropTypes.bool,

  /**
   * Event handler of title change with inline editing form.
   * @since 0.0.54
   */
  onTitleChange: PropTypes.func,

  /**
   * Event handler of closing section with X-sign at the right.
   * @since 0.0.54
   */
  onClose: PropTypes.func,

  /**
   * A callback executed when the section collapsing.
   * @since 3.26.0
   */
  onToggle: PropTypes.func,

  /**
   * Array of custom section action button at the right.
   * @since 0.0.54
   */
  buttons: PropTypes.arrayOf(PropTypes.element),

  /**
   * Vertical or horizontal section view.
   * Section view will be automatically switched if this parameter is not specified explicitly.
   * @since 0.3.0
   */
  vertical: PropTypes.bool,

  /**
   * Content of the `Section`.
   * @since 0.0.54
   */
  children: PropTypes.node,

  /**
   * @ignore
   */
  className: PropTypes.string,

  /**
   * @ignore
   */
  baseClassName: PropTypes.string,

  /**
   * @ignore
   */
  form: PropTypes.object
};
const defaultProps = {
  title: undefined,
  intent: undefined,
  collapsible: false,
  collapsed: false,
  onTitleChange: undefined,
  onClose: undefined,
  onToggle: undefined,
  buttons: undefined,
  vertical: undefined,
  children: undefined,
  className: undefined,
  baseClassName: `${CLS_PREFIX}section`,
  form: undefined
};
Section.propTypes = propTypes;
Section.defaultProps = defaultProps;
/**
 * `Section` component is used for dividing of complex content into groups for better readability
 * and comprehension of the presented information.
 * @since 0.0.54
 */

const SectionWrapper = props => {
  const form = useContext(FormContext);
  const verticalContext = useContext(VerticalContext);
  const vertical = props.vertical === undefined ? verticalContext : props.vertical;
  return /*#__PURE__*/React.createElement(Section, _extends({}, props, {
    form: form,
    vertical: vertical
  }));
};

SectionWrapper.displayName = 'Section';
SectionWrapper.propTypes = propTypes;
SectionWrapper.defaultProps = defaultProps;
SectionWrapper.WrappedComponent = Section;
export default SectionWrapper;