import _extends from "@babel/runtime/helpers/esm/extends";
import _inheritsLoose from "@babel/runtime/helpers/esm/inheritsLoose";
var _class, _ComboBoxView;
import React from 'react';
import { getRandomID, isNonNullable } from "../../../lib/utils";
import { Input } from "../../../components/Input";
import { InputLikeText } from "../../InputLikeText";
import { RenderLayer } from "../../RenderLayer";
import { Spinner } from "../../../components/Spinner";
import { CommonWrapper } from "../../CommonWrapper";
import { MobilePopup } from "../../MobilePopup";
import { responsiveLayout } from "../../../components/ResponsiveLayout/decorator";
import { rootNode, getRootNode } from "../../../lib/rootNode";
import { createPropsGetter } from "../../../lib/createPropsGetter";
import { ThemeContext } from "../../../lib/theming/ThemeContext";
import { LoadingIcon } from "../../icons2022/LoadingIcon";
import { Popup } from "../../Popup";
import { getMenuPositions } from "../../../lib/getMenuPositions";
import { ZIndex } from "../../ZIndex";
import { MaskedInput } from "../../../components/MaskedInput";
import { styles as MaskedInputStyles } from "../../../components/MaskedInput/MaskedInput.styles";
import { cx } from "../../../lib/theming/Emotion";
import { InternalTextareaWithLayout } from "../../InternalTextareaWithLayout/InternalTextareaWithLayout";
import { withSize } from "../../../lib/size/SizeDecorator";
import { ArrowDownIcon } from "../ArrowDownIcon";
import { ComboBoxMenu } from "../ComboBoxMenu";
import { ComboBoxRequestStatus } from "../CustomComboBoxTypes";
import { styles } from "../CustomComboBox.styles";
import { CustomComboBoxDataTids } from "../CustomComboBox";
import { getComboBoxTheme } from "../getComboBoxTheme";
export var ComboBoxViewIds = {
  menu: 'ComboBoxView__menu'
};
export var ComboBoxView = responsiveLayout(_class = rootNode(_class = withSize(_class = (_ComboBoxView = /*#__PURE__*/function (_React$Component) {
  function ComboBoxView() {
    var _this$props$value;
    var _this;
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    _this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
    _this.getProps = createPropsGetter(ComboBoxView.defaultProps);
    _this.mobileInput = null;
    _this.dropdownContainerRef = /*#__PURE__*/React.createRef();
    _this.menuId = ComboBoxViewIds.menu + getRandomID();
    _this.state = {
      anchorElement: null,
      clearCrossShowed: _this.props.showClearIcon === 'always' && !!((_this$props$value = _this.props.value) != null && _this$props$value.toString())
    };
    _this.getComboBoxMenu = function () {
      var _this$props = _this.props,
        items = _this$props.items,
        loading = _this$props.loading,
        opened = _this$props.opened,
        refMenu = _this$props.refMenu,
        maxMenuHeight = _this$props.maxMenuHeight,
        renderTotalCount = _this$props.renderTotalCount,
        renderNotFound = _this$props.renderNotFound,
        totalCount = _this$props.totalCount;
      var _this$getProps = _this.getProps(),
        repeatRequest = _this$getProps.repeatRequest,
        requestStatus = _this$getProps.requestStatus,
        renderItem = _this$getProps.renderItem,
        itemWrapper = _this$getProps.itemWrapper;
      return /*#__PURE__*/(
        React.createElement(ComboBoxMenu, {
          hasMargin: false,
          menuId: _this.menuId,
          items: items,
          loading: loading,
          maxMenuHeight: maxMenuHeight,
          onValueChange: _this.handleItemSelect,
          opened: opened,
          refMenu: refMenu,
          renderTotalCount: renderTotalCount,
          renderItem: renderItem,
          renderNotFound: renderNotFound,
          itemWrapper: itemWrapper,
          renderAddButton: _this.renderAddButton,
          repeatRequest: repeatRequest,
          requestStatus: requestStatus,
          totalCount: totalCount,
          isMobile: _this.isMobileLayout,
          size: _this.size
        })
      );
    };
    _this.renderMenu = function () {
      var _this$getProps2 = _this.getProps(),
        opened = _this$getProps2.opened,
        menuPos = _this$getProps2.menuPos,
        menuAlign = _this$getProps2.menuAlign;
      var anchorElement = _this.state.anchorElement;
      return opened && anchorElement && /*#__PURE__*/
      React.createElement(Popup, {
        opened: true,
        hasShadow: true,
        minWidth: "100%",
        anchorElement: anchorElement,
        priority: ZIndex.priorities.PopupMenu,
        positions: getMenuPositions(menuPos, menuAlign),
        disablePortal: _this.props.disablePortal,
        margin: parseInt(_this.theme.menuOffsetY) - 1,
        ref: _this.dropdownContainerRef
      }, _this.getComboBoxMenu());
    };
    _this.renderMobileMenu = function () {
      var rightIcon = null;
      var _this$props2 = _this.props,
        loading = _this$props2.loading,
        items = _this$props2.items,
        opened = _this$props2.opened,
        onFocus = _this$props2.onFocus,
        onInputValueChange = _this$props2.onInputValueChange,
        onInputKeyDown = _this$props2.onInputKeyDown,
        placeholder = _this$props2.placeholder,
        textValue = _this$props2.textValue;
      if (loading && items && !!items.length) {
        rightIcon = _this.renderSpinner();
      }
      var inputProps = {
        autoComplete: 'off',
        autoFocus: true,
        width: '100%',
        onFocus: onFocus,
        onValueChange: onInputValueChange,
        onKeyDown: onInputKeyDown,
        value: textValue,
        placeholder: placeholder,
        rightIcon: rightIcon
      };
      return opened && /*#__PURE__*/
      React.createElement(MobilePopup, {
        headerChildComponent: /*#__PURE__*/React.createElement(Input, _extends({
          ref: _this.refMobileInput
        }, inputProps)),
        onCloseRequest: _this.props.onMobileClose,
        opened: true
      }, _this.getComboBoxMenu());
    };
    _this.getParent = function () {
      return getRootNode(_this);
    };
    _this.renderAddButton = function () {
      return _this.getProps().renderAddButton(_this.props.textValue);
    };
    _this.handleMobileFocus = function () {
      var _this$mobileInput;
      _this.props.onInputClick == null || _this.props.onInputClick();
      (_this$mobileInput = _this.mobileInput) == null || _this$mobileInput.focus();
    };
    _this.handleItemSelect = function (item) {
      if (_this.props.onValueChange) {
        _this.props.onValueChange(item);
      }
      if (_this.isMobileLayout) {
        _this.props.onMobileClose == null || _this.props.onMobileClose();
      }
    };
    _this.refInput = function (input) {
      if (_this.props.refInput) {
        _this.props.refInput(input);
      }
      _this.input = input;
    };
    _this.renderSpinner = function () {
      return /*#__PURE__*/(
        React.createElement("span", {
          className: styles.spinnerWrapper()
        }, /*#__PURE__*/
        React.createElement(Spinner, {
          type: "mini",
          caption: "",
          dimmed: true
        }))
      );
    };
    _this.getRightIcon = function () {
      var _this$props3 = _this.props,
        loading = _this$props3.loading,
        items = _this$props3.items,
        drawArrow = _this$props3.drawArrow,
        rightIcon = _this$props3.rightIcon;
      var size = _this.size;
      if (loading && items && !!items.length) {
        return /*#__PURE__*/React.createElement(LoadingIcon, {
          size: size
        });
      }
      if (rightIcon || drawArrow) {
        return rightIcon || /*#__PURE__*/React.createElement(ArrowDownIcon, {
          size: size
        });
      }
      return null;
    };
    _this.refMobileInput = function (input) {
      _this.mobileInput = input;
    };
    return _this;
  }
  _inheritsLoose(ComboBoxView, _React$Component);
  var _proto = ComboBoxView.prototype;
  _proto.componentDidMount = function componentDidMount() {
    this.updateAnchorElement();
    if (this.props.autoFocus && this.props.onFocus) {
      this.props.onFocus();
    }
  };
  _proto.updateAnchorElement = function updateAnchorElement() {
    var parent = this.getParent();
    var anchorElement = this.state.anchorElement;
    if (anchorElement !== parent) {
      this.setState({
        anchorElement: parent
      });
    }
  };
  _proto.componentDidUpdate = function componentDidUpdate(prevProps) {
    var input = this.input,
      props = this.props;
    this.updateAnchorElement();
    if (props.editing && !prevProps.editing && input) {
      input.focus();
    }
  };
  _proto.render = function render() {
    var _this2 = this;
    return /*#__PURE__*/React.createElement(ThemeContext.Consumer, null, function (theme) {
      _this2.theme = getComboBoxTheme(theme, _this2.props.viewMode);
      return /*#__PURE__*/React.createElement(ThemeContext.Provider, {
        value: _this2.theme
      }, _this2.renderMain());
    });
  };
  _proto.renderMain = function renderMain() {
    var _this$props4 = this.props,
      onMouseEnter = _this$props4.onMouseEnter,
      onMouseLeave = _this$props4.onMouseLeave,
      onMouseOver = _this$props4.onMouseOver,
      opened = _this$props4.opened;
    var _this$getProps3 = this.getProps(),
      onClickOutside = _this$getProps3.onClickOutside,
      onFocusOutside = _this$getProps3.onFocusOutside,
      width = _this$getProps3.width;
    var isMobile = this.isMobileLayout;
    var input = this.renderInput();
    return /*#__PURE__*/React.createElement(CommonWrapper, this.props, /*#__PURE__*/React.createElement(RenderLayer, {
      onClickOutside: onClickOutside,
      onFocusOutside: onFocusOutside,
      active: opened
    }, /*#__PURE__*/React.createElement("span", {
      "data-tid": CustomComboBoxDataTids.comboBoxView,
      style: {
        width: width
      },
      className: styles.root(),
      onMouseEnter: onMouseEnter,
      onMouseLeave: onMouseLeave,
      onMouseOver: onMouseOver,
      ref: this.setRootNode
    }, input, isMobile ? this.renderMobileMenu() : this.renderMenu())));
  };
  _proto.renderInput = function renderInput() {
    var isMobile = this.isMobileLayout;
    var _this$props5 = this.props,
      id = _this$props5.id,
      align = _this$props5.align,
      borderless = _this$props5.borderless,
      disabled = _this$props5.disabled,
      editing = _this$props5.editing,
      error = _this$props5.error,
      onFocus = _this$props5.onFocus,
      onInputBlur = _this$props5.onInputBlur,
      onInputValueChange = _this$props5.onInputValueChange,
      onInputFocus = _this$props5.onInputFocus,
      onInputClick = _this$props5.onInputClick,
      onInputKeyDown = _this$props5.onInputKeyDown,
      placeholder = _this$props5.placeholder,
      textValue = _this$props5.textValue,
      value = _this$props5.value,
      warning = _this$props5.warning,
      refInputLikeText = _this$props5.refInputLikeText,
      leftIcon = _this$props5.leftIcon,
      inputMode = _this$props5.inputMode,
      ariaDescribedby = _this$props5['aria-describedby'],
      ariaLabel = _this$props5['aria-label'],
      showClearIcon = _this$props5.showClearIcon,
      mask = _this$props5.mask,
      maskChar = _this$props5.maskChar,
      formatChars = _this$props5.formatChars,
      onBeforePasteInMask = _this$props5.onBeforePasteInMask;
    var rightIcon = this.getRightIcon();
    var inputProps = {
      id: id,
      align: align,
      borderless: borderless,
      disabled: disabled,
      error: error,
      maxLength: this.props.maxLength,
      onBlur: isMobile ? undefined : onInputBlur,
      onValueChange: onInputValueChange,
      onFocus: onInputFocus,
      onClick: isMobile ? this.handleMobileFocus : onInputClick,
      leftIcon: leftIcon,
      rightIcon: rightIcon,
      value: textValue || '',
      onKeyDown: onInputKeyDown,
      placeholder: placeholder,
      width: '100%',
      ref: this.refInput,
      warning: warning,
      inputMode: inputMode,
      autoComplete: 'off',
      'aria-describedby': ariaDescribedby,
      'aria-controls': this.menuId,
      'aria-label': ariaLabel,
      showClearIcon: showClearIcon,
      size: this.size
    };
    var multilineTextareaProps = {
      autoResize: true,
      rows: 1,
      extraRow: false,
      maxRows: this.props.maxRows
    };
    if (this.props.viewMode === 'multiline' && !mask) {
      return /*#__PURE__*/React.createElement(InternalTextareaWithLayout, _extends({}, inputProps, multilineTextareaProps));
    }
    if (editing) {
      if (mask) {
        return /*#__PURE__*/React.createElement(MaskedInput, _extends({}, inputProps, {
          type: "text",
          mask: mask,
          maskChar: maskChar,
          formatChars: formatChars,
          onBeforePasteValue: onBeforePasteInMask
        }));
      }
      if (this.props.viewMode === 'multiline-editing') {
        return /*#__PURE__*/React.createElement(InternalTextareaWithLayout, _extends({}, inputProps, multilineTextareaProps));
      }
      return /*#__PURE__*/React.createElement(Input, inputProps);
    }
    var _this$getProps4 = this.getProps(),
      renderValue = _this$getProps4.renderValue;
    return /*#__PURE__*/React.createElement(InputLikeText, {
      id: id,
      align: align,
      borderless: borderless,
      error: error,
      onFocus: onFocus,
      leftIcon: leftIcon,
      rightIcon: rightIcon,
      disabled: disabled,
      warning: warning,
      placeholder: placeholder,
      size: this.size,
      width: "100%",
      ref: refInputLikeText,
      "aria-describedby": ariaDescribedby,
      "aria-controls": this.menuId,
      showClearIcon: showClearIcon,
      className: cx(mask && MaskedInputStyles.root(this.theme)),
      onClearCrossClick: this.props.onClearCrossClick
    }, isNonNullable(value) && renderValue ? renderValue(value) : null);
  };
  return ComboBoxView;
}(React.Component), _ComboBoxView.__KONTUR_REACT_UI__ = 'ComboBoxView', _ComboBoxView.displayName = 'ComboBoxView', _ComboBoxView.defaultProps = {
  renderItem: function renderItem(item) {
    return item;
  },
  renderValue: function renderValue(item) {
    return item;
  },
  renderAddButton: function renderAddButton() {
    return null;
  },
  repeatRequest: function repeatRequest() {
    return undefined;
  },
  requestStatus: ComboBoxRequestStatus.Unknown,
  onClickOutside: function onClickOutside() {/**/},
  onFocusOutside: function onFocusOutside() {/**/},
  width: 250,
  showClearIcon: 'never'
}, _ComboBoxView)) || _class) || _class) || _class;