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

import classNames from 'classnames';
import { Children, Component, isValidElement, useContext } from 'react';
import Measure from 'react-measure';
import { CLS_PREFIX } from '../../constants';
import Button from '../Button';
import FormContext from '../Form/FormContext';
import InPlaceEdit from '../InPlaceEdit';
import { isClickable } from '../utils';
import VerticalContext, { VERTICAL_BREAKPOINT } from '../VerticalContext';
import { jsx as _jsx } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
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;
};
export const SECTION_BASE_CLASS_NAME = `${CLS_PREFIX}section`;
const DEFAULT_PROPS = {
  title: undefined,
  intent: undefined,
  collapsible: false,
  collapsed: false,
  onTitleChange: undefined,
  onClose: undefined,
  onToggle: undefined,
  buttons: undefined,
  vertical: undefined,
  children: undefined,
  className: undefined,
  baseClassName: SECTION_BASE_CLASS_NAME,
  form: undefined
};
class Section extends Component {
  constructor() {
    super(...arguments);
    _defineProperty(this, "state", {
      vertical: false
    });
    _defineProperty(this, "handleResize", _ref => {
      let {
        bounds
      } = _ref;
      if (this.props.vertical !== undefined || !bounds) {
        return;
      }
      this.setState({
        vertical: bounds.width < VERTICAL_BREAKPOINT
      });
    });
    _defineProperty(this, "handleCollapse", e => {
      if (isClickable(e)) {
        return;
      }
      this.setState(_ref2 => {
        let {
          collapsed
        } = _ref2;
        return {
          collapsed: !collapsed
        };
      }, () => {
        this.props.onToggle?.(this.state.collapsed ?? false);
      });
    });
  }
  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(_ref3) {
    let {
      baseClassName,
      collapsible
    } = _ref3;
    const {
      collapsed
    } = this.state;
    return collapsible && /*#__PURE__*/_jsx(Button, {
      ghost: true,
      className: classNames(`${baseClassName}__control-button`, `${baseClassName}__control-button--collapse`),
      icon: {
        name: 'chevron-up',
        flipVertical: collapsed
      },
      onClick: this.handleCollapse
    });
  }
  renderCloseButton(_ref4) {
    let {
      baseClassName,
      onClose,
      buttons
    } = _ref4;
    return (onClose || buttons) && /*#__PURE__*/_jsxs("div", {
      className: `${baseClassName}__header-buttons`,
      children: [buttons, onClose && /*#__PURE__*/_jsx(Button, {
        ghost: true,
        className: classNames(`${baseClassName}__control-button`, `${baseClassName}__control-button--close`),
        onClick: onClose,
        icon: "cross-mark"
      })]
    });
  }
  renderTitle(_ref5) {
    let {
      baseClassName,
      title,
      onTitleChange
    } = _ref5;
    return title && /*#__PURE__*/_jsx(InPlaceEdit, {
      className: `${baseClassName}__title`,
      value: title,
      onChange: onTitleChange,
      onClick: e => {
        const button = e.target?.closest(`.${baseClassName}__header`)?.querySelector(`.${baseClassName}__control-button`);
        button?.click();
      }
    });
  }
  renderContent(_ref6) {
    let {
      collapsible,
      children
    } = _ref6;
    const {
      collapsed
    } = this.state;
    if (collapsible && collapsed) {
      return null;
    }
    return children;
  }
  render() {
    const {
      baseClassName = SECTION_BASE_CLASS_NAME,
      className,
      intent,
      collapsible = false,
      title,
      collapsed,
      onTitleChange,
      onClose,
      onToggle,
      buttons,
      vertical: verticalProp,
      children,
      form,
      ...props
    } = this.props;
    const vertical = verticalProp === undefined ? this.state.vertical : verticalProp;
    return /*#__PURE__*/_jsx(VerticalContext.Provider, {
      value: vertical,
      children: /*#__PURE__*/_jsx(Measure, {
        onResize: this.handleResize,
        bounds: true,
        children: _ref7 => {
          let {
            measureRef
          } = _ref7;
          return /*#__PURE__*/_jsxs("div", {
            ref: measureRef,
            className: classNames(baseClassName, {
              [`${baseClassName}--${intent}`]: intent,
              [`${baseClassName}--collapsible`]: collapsible,
              [`${baseClassName}--collapsed`]: this.state.collapsed,
              [`${baseClassName}--vertical`]: vertical
            }, className),
            ...props,
            children: [title && /*#__PURE__*/_jsxs("div", {
              className: `${baseClassName}__header`,
              children: [this.renderCollapseButton({
                baseClassName,
                collapsible
              }), this.renderTitle({
                baseClassName,
                title,
                onTitleChange
              }), this.renderCloseButton({
                baseClassName,
                onClose,
                buttons
              })]
            }), this.renderContent({
              collapsible,
              children
            })]
          });
        }
      })
    });
  }
}

/**
 * `Section` component is used for dividing of complex content into groups for better readability
 * and comprehension of the presented information.
 * @since 0.0.54
 */
_defineProperty(Section, "defaultProps", DEFAULT_PROPS);
const SectionWrapper = props => {
  const form = useContext(FormContext);
  const verticalContext = useContext(VerticalContext);
  const vertical = props.vertical === undefined ? verticalContext : props.vertical;
  return /*#__PURE__*/_jsx(Section, {
    ...props,
    form: form,
    vertical: vertical
  });
};
SectionWrapper.displayName = 'Section';
SectionWrapper.defaultProps = DEFAULT_PROPS;
SectionWrapper.WrappedComponent = Section;
export default SectionWrapper;