import _extends from "@babel/runtime/helpers/esm/extends";
import _inheritsLoose from "@babel/runtime/helpers/esm/inheritsLoose";
var _class, _Switcher;
import React from 'react';
import { isKeyArrowHorizontal, isKeyArrowLeft, isKeyEnter } from "../../../lib/events/keyboard/identifiers";
import { getButtonCorners, Group } from "../../Group";
import { Button } from "../../Button";
import { ThemeContext } from "../../../lib/theming/ThemeContext";
import { CommonWrapper } from "../../../internal/CommonWrapper";
import { cx } from "../../../lib/theming/Emotion";
import { rootNode } from "../../../lib/rootNode";
import { isThemeGTE } from "../../../lib/theming/ThemeHelpers";
import { ReactUIFeatureFlagsContext } from "../../../lib/featureFlagsContext";
import { styles } from "../Switcher.styles";
import { getSwitcherTheme } from "../switcherTheme";
import { mod } from "../helpers";
export var SwitcherDataTids = {
  root: 'Switcher__root'
};

/**
 * Переключатель `Switcher` — это замена RadioGroup.
 *
 * Не используйте переключатель в качестве навигации, для этого лучше подходят Tabs.
 */
export var Switcher = rootNode(_class = (_Switcher = /*#__PURE__*/function (_React$Component) {
  function Switcher() {
    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.state = {
      focusedIndex: null
    };
    _this.selectItem = function (value) {
      if (_this.props.onValueChange) {
        _this.props.onValueChange(value);
      }
    };
    _this._extractPropsFromItem = function (item) {
      return typeof item === 'object' ? item : {
        label: item,
        value: item
      };
    };
    _this._extractValuesFromItems = function () {
      return _this.props.items.map(function (item) {
        var _this$_extractPropsFr = _this._extractPropsFromItem(item),
          value = _this$_extractPropsFr.value;
        return value;
      });
    };
    _this._focus = function (index) {
      _this.setState({
        focusedIndex: index
      });
    };
    _this.handleKey = function (e) {
      var focusedIndex = _this.state.focusedIndex;
      if (typeof focusedIndex !== 'number') {
        return;
      }
      if (isKeyEnter(e)) {
        if (_this.props.onValueChange) {
          var _this$_extractPropsFr2 = _this._extractPropsFromItem(_this.props.items[focusedIndex]),
            value = _this$_extractPropsFr2.value,
            buttonProps = _this$_extractPropsFr2.buttonProps;
          if (!(buttonProps != null && buttonProps.disabled)) {
            _this.selectItem(value);
          }
        }
        return;
      }
      if (isKeyArrowHorizontal(e)) {
        e.preventDefault();
        _this.move(isKeyArrowLeft(e));
      }
    };
    _this.move = function (left) {
      var selectedIndex = _this.state.focusedIndex;
      if (typeof selectedIndex !== 'number') {
        return;
      }
      var newFocusedIndex = _this._getNextFocusedIndex(left, selectedIndex);
      _this._focus(newFocusedIndex);
    };
    _this._getNextFocusedIndex = function (left, focusedIndex) {
      var _this$props = _this.props,
        items = _this$props.items,
        disabled = _this$props.disabled;
      if (disabled) {
        return focusedIndex;
      }
      for (var i = 1; i < items.length; i++) {
        var index = mod(focusedIndex + (left ? -i : i), items.length);
        var _this$_extractPropsFr3 = _this._extractPropsFromItem(items[index]),
          buttonProps = _this$_extractPropsFr3.buttonProps;
        if (!(buttonProps != null && buttonProps.disabled)) {
          return index;
        }
      }
      return focusedIndex;
    };
    _this._handleFocus = function () {
      var value = _this.props.value;
      var items = _this._extractValuesFromItems();
      var currentIndex = [].concat(items).indexOf(value);
      var index = currentIndex > -1 ? currentIndex : 0;
      _this.setState({
        focusedIndex: index
      });
    };
    _this._handleBlur = function () {
      _this.setState({
        focusedIndex: null
      });
    };
    _this._renderItems = function () {
      var _this$props2 = _this.props,
        items = _this$props2.items,
        value = _this$props2.value,
        size = _this$props2.size,
        width = _this$props2.width,
        disabled = _this$props2.disabled,
        role = _this$props2.role,
        renderItem = _this$props2.renderItem;
      return items.map(function (item, i) {
        var _this$_extractPropsFr4 = _this._extractPropsFromItem(item),
          ariaLabel = _this$_extractPropsFr4['aria-label'],
          label = _this$_extractPropsFr4.label,
          itemValue = _this$_extractPropsFr4.value,
          customButtonProps = _this$_extractPropsFr4.buttonProps;
        var isChecked = value === itemValue;
        var commonButtonProps = {
          'aria-checked': isChecked,
          role: role,
          checked: isChecked,
          visuallyFocused: _this.state.focusedIndex === i,
          onClick: function onClick() {
            _this.selectItem(itemValue);
          },
          disableFocus: true,
          size: size,
          disabled: disabled,
          corners: getButtonCorners(i === 0, i === items.length - 1)
        };
        var buttonProps = _extends({}, commonButtonProps, customButtonProps);
        if (!buttonProps.width && width) {
          buttonProps.width = '100%';
        }
        var renderDefault = function renderDefault() {
          return _this.renderDefaultItem(label, itemValue, buttonProps, ariaLabel);
        };
        return renderItem ? renderItem(label, itemValue, buttonProps, renderDefault, ariaLabel) : renderDefault();
      });
    };
    _this.renderDefaultItem = function (label, value, buttonProps, ariaLabel) {
      return /*#__PURE__*/(
        React.createElement(Button, _extends({
          "aria-label": ariaLabel,
          key: value
        }, buttonProps), label)
      );
    };
    _this.getLabelSizeClassName = function () {
      switch (_this.props.size) {
        case 'large':
          return styles.captionLarge(_this.theme);
        case 'medium':
          return styles.captionMedium(_this.theme);
        case 'small':
        default:
          return styles.captionSmall(_this.theme);
      }
    };
    return _this;
  }
  _inheritsLoose(Switcher, _React$Component);
  var _proto = Switcher.prototype;
  _proto.render = function render() {
    var _this2 = this;
    return /*#__PURE__*/React.createElement(ThemeContext.Consumer, null, function (theme) {
      _this2.theme = getSwitcherTheme(theme);
      return /*#__PURE__*/React.createElement(ThemeContext.Provider, {
        value: _this2.theme
      }, _this2.renderMain());
    });
  };
  _proto.renderMain = function renderMain() {
    var _cx, _cx2;
    var inputProps = {
      type: 'checkbox',
      onKeyDown: this.handleKey,
      onFocus: this._handleFocus,
      onBlur: this._handleBlur,
      className: styles.input()
    };
    var isThemeGTE_5_1 = isThemeGTE(this.theme, '5.1');
    var isTheme_5_0 = !isThemeGTE_5_1;
    var items = /*#__PURE__*/React.createElement(ReactUIFeatureFlagsContext.Provider, {
      value: {
        groupAddHintAndTooltipSupport: true
      }
    }, /*#__PURE__*/React.createElement(Group, {
      width: '100%'
    }, this._renderItems()));
    var captionClassName = cx(styles.caption(this.theme), this.getLabelSizeClassName());
    var wrapperClassName = cx(styles.wrap(), (_cx = {}, _cx[styles.error5_1(this.theme)] = isThemeGTE_5_1 && this.props.error, _cx[styles.wrapCustomWidth()] = this.props.width !== undefined, _cx));
    var errorClassName = cx((_cx2 = {}, _cx2[styles.error(this.theme)] = isTheme_5_0 && this.props.error, _cx2));
    return /*#__PURE__*/React.createElement(CommonWrapper, _extends({
      rootNodeRef: this.setRootNode
    }, this.props), /*#__PURE__*/React.createElement("div", {
      "data-tid": SwitcherDataTids.root,
      className: styles.root(),
      style: {
        width: this.props.width
      }
    }, this.props.caption ? /*#__PURE__*/React.createElement("div", {
      className: captionClassName
    }, this.props.caption) : null, /*#__PURE__*/React.createElement("div", {
      className: wrapperClassName
    }, /*#__PURE__*/React.createElement("input", inputProps), isThemeGTE_5_1 ? items : /*#__PURE__*/React.createElement("div", {
      className: errorClassName
    }, items))));
  };
  return Switcher;
}(React.Component), _Switcher.__KONTUR_REACT_UI__ = 'Switcher', _Switcher.displayName = 'Switcher', _Switcher.defaultProps = {
  role: 'switch'
}, _Switcher)) || _class;