import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import _inheritsLoose from "@babel/runtime/helpers/esm/inheritsLoose";
var _excluded = ["disabled", "warning", "error", "size", "focused", "onMouseOver", "onMouseEnter", "onMouseLeave", "onValueChange"];
var _class, _Radio;
import React from 'react';
import { globalObject } from '@skbkontur/global-object';
import { ThemeContext } from "../../../lib/theming/ThemeContext";
import { CommonWrapper } from "../../../internal/CommonWrapper";
import { cx } from "../../../lib/theming/Emotion";
import { keyListener } from "../../../lib/events/keyListener";
import { rootNode } from "../../../lib/rootNode";
import { fixFirefoxModifiedClickOnLabel } from "../../../lib/events/fixFirefoxModifiedClickOnLabel";
import { isEdge, isIE11 } from "../../../lib/client";
import { RadioGroupContext } from "../../RadioGroup/RadioGroupContext";
import { createPropsGetter } from "../../../lib/createPropsGetter";
import { FocusControlWrapper } from "../../../internal/FocusControlWrapper";
import { withSize } from "../../../lib/size/SizeDecorator";
import { styles, globalClasses } from "../Radio.styles";
export var RadioDataTids = {
  root: 'Radio__root'
};

/** Радиокнопка позволяет выбрать одно значение из нескольких. Подходит при небольшом количестве вариантов — 2–5.
 *
 * Для создания группы радиокнопок используйте специальный контейнер — компонент [RadioGroup](https://tech.skbkontur.ru/kontur-ui/?path=/docs/react-ui_input-data-radiogroup--docs).
 */
export var Radio = rootNode(_class = withSize(_class = (_Radio = /*#__PURE__*/function (_React$Component) {
  function Radio() {
    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 = {
      focusedByKeyboard: false
    };
    _this.getProps = createPropsGetter(Radio.defaultProps);
    _this.context = _this.context;
    _this.inputEl = /*#__PURE__*/React.createRef();
    _this.renderMain = function (props) {
      var _cx, _cx2;
      var _props$disabled = props.disabled,
        disabled = _props$disabled === void 0 ? _this.context.disabled : _props$disabled,
        _props$warning = props.warning,
        warning = _props$warning === void 0 ? _this.context.warning : _props$warning,
        _props$error = props.error,
        error = _props$error === void 0 ? _this.context.error : _props$error,
        size = props.size,
        focused = props.focused,
        onMouseOver = props.onMouseOver,
        onMouseEnter = props.onMouseEnter,
        onMouseLeave = props.onMouseLeave,
        onValueChange = props.onValueChange,
        rest = _objectWithoutPropertiesLoose(props, _excluded);
      var radioProps = {
        className: cx((_cx = {}, _cx[styles.circle(_this.theme)] = true, _cx[_this.getCircleSizeClassName()] = true, _cx[styles.checked(_this.theme)] = _this.props.checked, _cx[_this.getCheckedSizeClassName()] = _this.props.checked, _cx[styles.focus(_this.theme)] = _this.getProps().focused || _this.state.focusedByKeyboard, _cx[styles.error(_this.theme)] = error, _cx[styles.warning(_this.theme)] = warning, _cx[styles.disabled(_this.theme)] = disabled, _cx[styles.checkedDisabled(_this.theme)] = _this.props.checked && disabled, _cx[globalClasses.circle] = true, _cx))
      };
      var value;
      if (typeof _this.props.value === 'string' || typeof _this.props.value === 'number') {
        value = _this.props.value;
      }
      var inputProps = _extends({}, rest, {
        type: 'radio',
        className: styles.input(),
        disabled: disabled,
        tabIndex: _this.props.tabIndex,
        value: value,
        ref: _this.inputEl,
        onChange: _this.handleChange,
        onFocus: _this.handleFocus,
        onBlur: _this.handleBlur
      });
      var labelProps = {
        className: cx(styles.root(_this.theme), _this.getRootSizeClassName(), (_cx2 = {}, _cx2[styles.rootChecked(_this.theme)] = _this.props.checked, _cx2[styles.rootIE11()] = isIE11 || isEdge, _cx2)),
        onMouseOver: _this.handleMouseOver,
        onMouseEnter: _this.handleMouseEnter,
        onMouseLeave: _this.handleMouseLeave,
        onClick: fixFirefoxModifiedClickOnLabel(_this.inputEl)
      };
      if (_this._isInRadioGroup()) {
        var _cx3, _cx4;
        var checked = _this.props.value === _this.context.activeItem;
        inputProps.checked = checked;
        inputProps.name = _this.context.name;
        inputProps.suppressHydrationWarning = true;
        labelProps.className = cx(styles.root(_this.theme), _this.getRootSizeClassName(), (_cx3 = {}, _cx3[styles.rootChecked(_this.theme)] = checked, _cx3[styles.rootIE11()] = isIE11 || isEdge, _cx3));
        radioProps.className = cx(radioProps.className, (_cx4 = {}, _cx4[styles.checked(_this.theme)] = checked, _cx4[_this.getCheckedSizeClassName()] = checked, _cx4[styles.checkedDisabled(_this.theme)] = checked && disabled, _cx4));
      }
      return /*#__PURE__*/(
        React.createElement("label", _extends({
          "data-tid": RadioDataTids.root
        }, labelProps), /*#__PURE__*/
        React.createElement(FocusControlWrapper, {
          onBlurWhenDisabled: _this.resetFocus
        }, /*#__PURE__*/
        React.createElement("input", inputProps)), /*#__PURE__*/
        React.createElement("span", radioProps, /*#__PURE__*/
        React.createElement("span", {
          className: styles.placeholder()
        })), _this.props.children && _this.renderCaption())
      );
    };
    _this._isInRadioGroup = function () {
      return Boolean(_this.context.name);
    };
    _this.handleChange = function (e) {
      _this.props.onValueChange == null || _this.props.onValueChange(_this.props.value);
      if (_this._isInRadioGroup()) {
        _this.context.onSelect(_this.props.value);
      }
      _this.props.onChange == null || _this.props.onChange(e);
    };
    _this.handleMouseOver = function (e) {
      _this.props.onMouseOver == null || _this.props.onMouseOver(e);
    };
    _this.handleMouseEnter = function (e) {
      _this.props.onMouseEnter == null || _this.props.onMouseEnter(e);
    };
    _this.handleMouseLeave = function (e) {
      _this.props.onMouseLeave == null || _this.props.onMouseLeave(e);
    };
    _this.handleFocus = function (e) {
      if (!_this.context.disabled) {
        // focus event fires before keyDown eventlistener
        // so we should check tabPressed in async way
        globalObject.requestAnimationFrame == null || globalObject.requestAnimationFrame(function () {
          if (keyListener.isArrowPressed || keyListener.isTabPressed) {
            _this.setState({
              focusedByKeyboard: true
            });
          }
        });
        if (_this.props.onFocus) {
          _this.props.onFocus(e);
        }
      }
    };
    _this.resetFocus = function () {
      return _this.setState({
        focusedByKeyboard: false
      });
    };
    _this.handleBlur = function (e) {
      _this.resetFocus();
      _this.props.onBlur == null || _this.props.onBlur(e);
    };
    return _this;
  }
  _inheritsLoose(Radio, _React$Component);
  var _proto = Radio.prototype;
  _proto.getRootSizeClassName = function getRootSizeClassName() {
    switch (this.size) {
      case 'large':
        return styles.rootLarge(this.theme);
      case 'medium':
        return styles.rootMedium(this.theme);
      case 'small':
      default:
        return styles.rootSmall(this.theme);
    }
  };
  _proto.getCircleSizeClassName = function getCircleSizeClassName() {
    switch (this.size) {
      case 'large':
        return styles.circleLarge(this.theme);
      case 'medium':
        return styles.circleMedium(this.theme);
      case 'small':
      default:
        return styles.circleSmall(this.theme);
    }
  };
  _proto.getCheckedSizeClassName = function getCheckedSizeClassName() {
    switch (this.size) {
      case 'large':
        return styles.checkedLarge(this.theme);
      case 'medium':
        return styles.checkedMedium(this.theme);
      case 'small':
      default:
        return styles.checkedSmall(this.theme);
    }
  };
  _proto.render = function render() {
    var _this2 = this;
    return /*#__PURE__*/React.createElement(ThemeContext.Consumer, null, function (theme) {
      _this2.theme = theme;
      return /*#__PURE__*/React.createElement(CommonWrapper, _extends({
        rootNodeRef: _this2.setRootNode
      }, _this2.getProps()), _this2.renderMain);
    });
  } /** Программно устанавливает фокус на радиокнопку. Появляется фокусная обводка, элемент получает клавиатурные события и воспринимается как текущий элемент для чтения скринридерами.
    * @public
    */;
  _proto.focus = function focus() {
    var _this$inputEl$current;
    keyListener.isTabPressed = true;
    (_this$inputEl$current = this.inputEl.current) == null || _this$inputEl$current.focus();
  } /** Программно снимает фокус с радиокнопки.
    * @public
    */;
  _proto.blur = function blur() {
    var _this$inputEl$current2;
    (_this$inputEl$current2 = this.inputEl.current) == null || _this$inputEl$current2.blur();
  };
  _proto.renderCaption = function renderCaption() {
    var _cx5;
    var captionClassNames = cx((_cx5 = {}, _cx5[styles.caption(this.theme)] = true, _cx5[styles.captionDisabled(this.theme)] = !!(this.props.disabled || this.context.disabled), _cx5[styles.captionIE11()] = isIE11 || isEdge, _cx5));
    return /*#__PURE__*/React.createElement("div", {
      className: captionClassNames
    }, this.props.children);
  };
  return Radio;
}(React.Component), _Radio.__KONTUR_REACT_UI__ = 'Radio', _Radio.displayName = 'Radio', _Radio.defaultProps = {
  focused: false
}, _Radio.contextType = RadioGroupContext, _Radio)) || _class) || _class;