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

import classNames from 'classnames';
import { Component, createRef } from 'react';
import { CLS_PREFIX } from '../../constants';
import calculateNodeHeight from './calculateNodeHeight';
import { jsx as _jsx } from "react/jsx-runtime";
const getMinMax = rows => {
  if (typeof rows === 'number') {
    return {
      minRows: rows
    };
  } else if (typeof rows === 'object' && typeof rows.min === 'number' && typeof rows.max === 'number') {
    return {
      minRows: rows.min,
      maxRows: rows.max
    };
  }
  return null;
};
const AVAILABLE_SIZES = ['sm', 'md', 'lg', 'xl', 'fill'];

/**
 * `TextArea` is used for entering long text (like email body, descriptions, comments).
 * @since 1.9.0
 */

class TextArea extends Component {
  constructor() {
    super(...arguments);
    _defineProperty(this, "state", {
      textareaStyles: null
    });
    _defineProperty(this, "rootRef", /*#__PURE__*/createRef());
    _defineProperty(this, "handleChange", e => {
      const {
        autoheight,
        onChange
      } = this.props;
      if (autoheight) {
        this.adjustHeight();
      }
      if (typeof onChange === 'function') {
        onChange(e);
      }
    });
  }
  static getDerivedStateFromProps(_ref) {
    let {
      rows
    } = _ref;
    if (rows) {
      return getMinMax(rows);
    }
    return null;
  }
  componentDidMount() {
    this.adjustHeight();
  }
  componentDidUpdate(prevProps) {
    const {
      autoheight
    } = this.props;
    if (autoheight !== prevProps.autoheight) {
      this.adjustHeight();
    }
  }
  adjustHeight() {
    const {
      autoheight
    } = this.props;
    if (!autoheight) {
      this.setState({
        textareaStyles: null
      });
      return;
    }
    const {
      minRows,
      maxRows
    } = this.state;
    if (this.rootRef.current) {
      const textareaStyles = calculateNodeHeight(this.rootRef.current, false, minRows, maxRows);
      this.setState({
        textareaStyles
      });
    }
  }
  render() {
    const {
      baseClassName,
      className,
      rows,
      size,
      autoheight,
      onChange,
      ...other
    } = this.props;
    const {
      textareaStyles,
      minRows
    } = this.state;
    const useSizeModifier = size && AVAILABLE_SIZES.indexOf(size) !== -1;
    return /*#__PURE__*/_jsx("textarea", {
      className: classNames(baseClassName, {
        [`${baseClassName}--size-${size}`]: useSizeModifier
      }, className),
      ref: this.rootRef,
      style: textareaStyles,
      onChange: this.handleChange,
      rows: minRows,
      ...other
    });
  }
}
_defineProperty(TextArea, "defaultProps", {
  baseClassName: `${CLS_PREFIX}textarea`,
  className: null,
  rows: 4,
  size: 'md',
  autoheight: false,
  onChange: null
});
export default TextArea;