import _createForOfIteratorHelperLoose from "@babel/runtime/helpers/esm/createForOfIteratorHelperLoose";
import _extends from "@babel/runtime/helpers/esm/extends";
import _inheritsLoose from "@babel/runtime/helpers/esm/inheritsLoose";
var _class, _RadioGroup;
import React from 'react';
import invariant from 'invariant';
import { getRandomID, isNonNullable } from "../../../lib/utils";
import { Radio } from "../../Radio";
import { createPropsGetter } from "../../../lib/createPropsGetter";
import { FocusTrap } from "../../../internal/FocusTrap";
import { CommonWrapper } from "../../../internal/CommonWrapper";
import { cx } from "../../../lib/theming/Emotion";
import { rootNode } from "../../../lib/rootNode";
import { getVisualStateDataAttributes } from "../../../internal/CommonWrapper/utils/getVisualStateDataAttributes";
import { getFullReactUIFlagsContext, ReactUIFeatureFlagsContext } from "../../../lib/featureFlagsContext";
import { styles } from "../RadioGroup.styles";
import { Prevent } from "../Prevent";
import { RadioGroupContext } from "../RadioGroupContext";
export var RadioGroupDataTids = {
  root: 'RadioGroup__root'
};

/** Группирует радиокнопки. Контейнер для компонента [Radio](https://tech.skbkontur.ru/kontur-ui/?path=/docs/react-ui_input-data-radio--docs). */
export var RadioGroup = rootNode(_class = (_RadioGroup = /*#__PURE__*/function (_React$Component) {
  function RadioGroup(props) {
    var _this;
    _this = _React$Component.call(this, props) || this;
    _this.name = getRandomID();
    _this.getProps = createPropsGetter(RadioGroup.defaultProps);
    _this.getRadioGroupContextValue = function () {
      return {
        activeItem: _this.getValue(),
        onSelect: _this.handleSelect,
        name: _this.getName(),
        disabled: _this.props.disabled,
        error: _this.props.error,
        warning: _this.props.warning
      };
    };
    _this.getValue = function () {
      return _this.isControlled() ? _this.props.value : _this.state.activeItem;
    };
    _this.getName = function () {
      return _this.props.name || _this.name;
    };
    _this.isControlled = function () {
      return isNonNullable(_this.props.value);
    };
    _this.handleSelect = function (value) {
      if (!_this.isControlled()) {
        _this.setState({
          activeItem: value
        });
      }
      if (_this.props.onValueChange) {
        _this.props.onValueChange(value);
      }
    };
    _this.renderRadio = function (itemValue, data, index) {
      var _cx;
      var itemProps = {
        key: _this.getKeyByItem(itemValue),
        className: cx((_cx = {}, _cx[styles.item()] = true, _cx[styles.itemFirst()] = index === 0, _cx[styles.itemInline()] = !!_this.props.inline, _cx))
      };
      return /*#__PURE__*/(
        React.createElement("span", _extends({}, itemProps, {
          role: "presentation"
        }), /*#__PURE__*/
        React.createElement(Radio, {
          value: itemValue
        }, _this.getProps().renderItem(itemValue, data)))
      );
    };
    _this.getKeyByItem = function (itemValue) {
      if (_this.props.toKey) {
        return _this.props.toKey(itemValue);
      }
      return typeof itemValue === 'string' || typeof itemValue === 'number' ? itemValue : undefined;
    };
    _this.ref = function (element) {
      _this.node = element;
    };
    _this.state = {
      activeItem: _this.props.defaultValue
    };
    return _this;
  }
  _inheritsLoose(RadioGroup, _React$Component);
  var _proto = RadioGroup.prototype;
  _proto.render = function render() {
    var _this2 = this;
    var _this$props = this.props,
      width = _this$props.width,
      onMouseLeave = _this$props.onMouseLeave,
      onMouseOver = _this$props.onMouseOver,
      onMouseEnter = _this$props.onMouseEnter,
      onBlur = _this$props.onBlur,
      ariaDescribedby = _this$props['aria-describedby'],
      disabled = _this$props.disabled;
    var style = {
      width: width != null ? width : 'auto'
    };
    var handlers = {
      onMouseOver: onMouseOver,
      onMouseEnter: onMouseEnter,
      onMouseLeave: onMouseLeave
    };
    return /*#__PURE__*/React.createElement(ReactUIFeatureFlagsContext.Consumer, null, function (flags) {
      var _cx2;
      _this2.featureFlags = getFullReactUIFlagsContext(flags);
      return /*#__PURE__*/React.createElement(CommonWrapper, _extends({
        rootNodeRef: _this2.setRootNode
      }, _this2.props, getVisualStateDataAttributes({
        disabled: disabled
      })), /*#__PURE__*/React.createElement(FocusTrap, {
        onBlur: onBlur
      }, /*#__PURE__*/React.createElement("span", _extends({
        "data-tid": RadioGroupDataTids.root,
        ref: _this2.ref,
        style: style,
        className: cx((_cx2 = {}, _cx2[styles.root()] = true, _cx2[styles.removeBaselineSpacer()] = _this2.featureFlags.radioGroupRemoveBaselineSpacer, _cx2)),
        role: "radiogroup"
      }, handlers, {
        "aria-describedby": ariaDescribedby
      }), /*#__PURE__*/React.createElement(RadioGroupContext.Provider, {
        value: _this2.getRadioGroupContextValue()
      }, _this2.renderChildren()))));
    });
  } /** Программно устанавливает фокус на радиокнопку. Появляется фокусная обводка, элемент получает клавиатурные события и воспринимается как текущий элемент для чтения скринридерами.
    * @public
    */;
  _proto.focus = function focus() {
    var node = this.node;
    if (!node) {
      return;
    }
    var radio = node.querySelector('input[type="radio"]:checked'); // If no checked radios, try get first radio
    if (!radio || radio.disabled) {
      radio = node.querySelector('input[type="radio"]:not([disabled])');
    }
    if (radio) {
      radio.focus();
    }
  };
  _proto.renderChildren = function renderChildren() {
    var _this$props2 = this.props,
      items = _this$props2.items,
      children = _this$props2.children;
    invariant(!items && children || items && !children, 'Either items or children must be passed, not both');
    return items ? mapItems(this.renderRadio, items) : children;
  };
  return RadioGroup;
}(React.Component), _RadioGroup.__KONTUR_REACT_UI__ = 'RadioGroup', _RadioGroup.displayName = 'RadioGroup', _RadioGroup.defaultProps = {
  renderItem: renderItem
}, _RadioGroup.Prevent = Prevent, _RadioGroup)) || _class;
function renderItem(_value, data) {
  return data;
}
function mapItems(fn, items) {
  var result = [];
  var index = 0;
  for (var _iterator = _createForOfIteratorHelperLoose(items), _step; !(_step = _iterator()).done;) {
    var entry = _step.value;
    var _normalizeEntry = normalizeEntry(entry),
      value = _normalizeEntry[0],
      data = _normalizeEntry[1];
    result.push(fn(value, data, index));
    ++index;
  }
  return result;
}
function normalizeEntry(entry) {
  if (!Array.isArray(entry)) {
    return [entry, entry];
  }
  return entry;
}