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

import { Component, createRef } from 'react';
import classNames from 'classnames';
import Measure from 'react-measure';
import { CLS_PREFIX } from '../../constants';
import Translate from '../Translate';
import Link from '../Link';
import { jsx as _jsx } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
/**
 * `Cuttable` component is used for showing and hiding part of content.
 * @since 0.0.42
 */
class Cuttable extends Component {
  constructor() {
    super(...arguments);
    _defineProperty(this, "state", {
      collapsed: undefined,
      autofit: true
    });
    _defineProperty(this, "contentRef", /*#__PURE__*/createRef());
    _defineProperty(this, "handleToggle", () => {
      this.setState(_ref => {
        let {
          collapsed
        } = _ref;
        return {
          collapsed: !collapsed,
          autofit: false
        };
      });
    });
    _defineProperty(this, "handleResize", () => {
      if (!this.state.autofit) {
        return;
      }
      const content = this.contentRef.current;
      if (content && content.scrollHeight > content.clientHeight) {
        this.setState({
          collapsed: this.props.collapsed
        });
      }
    });
  }
  render() {
    const {
      baseClassName,
      className,
      children,
      collapsed,
      maxHeight,
      locale,
      ...props
    } = this.props;
    const showMoreLessKey = this.state.collapsed ? 'showMore' : 'showLess';
    return /*#__PURE__*/_jsxs("div", {
      className: classNames(baseClassName, {
        [`${baseClassName}--collapse`]: this.state.collapsed === true,
        [`${baseClassName}--expand`]: this.state.collapsed === false
      }, className),
      ...props,
      children: [/*#__PURE__*/_jsx(Measure, {
        onResize: this.handleResize,
        innerRef: el => {
          this.contentRef.current = el;
        },
        children: _ref2 => {
          let {
            measureRef
          } = _ref2;
          return /*#__PURE__*/_jsx("div", {
            className: `${baseClassName}__content`,
            style: {
              maxHeight
            },
            ref: measureRef,
            children: children
          });
        }
      }), this.state.collapsed !== undefined && /*#__PURE__*/_jsx("div", {
        className: `${baseClassName}__action`,
        children: /*#__PURE__*/_jsx(Link, {
          onClick: this.handleToggle,
          children: /*#__PURE__*/_jsx(Translate, {
            content: `Cuttable.${showMoreLessKey}`,
            fallback: locale[showMoreLessKey]
          })
        })
      })]
    });
  }
}
_defineProperty(Cuttable, "defaultProps", {
  collapsed: true,
  maxHeight: '7rem',
  locale: {
    showMore: 'Show more',
    showLess: 'Show less'
  },
  baseClassName: `${CLS_PREFIX}cuttable`
});
export default Cuttable;