function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }

import React from 'react';
import PropTypes from 'prop-types';
/**
 * @category controls
 * @component radio
 * @variations collab-ui-react
 */

var RadioGroup =
/*#__PURE__*/
function (_React$Component) {
  _inheritsLoose(RadioGroup, _React$Component);

  function RadioGroup() {
    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 = {
      values: []
    };

    _this.handleToggle = function (value) {
      var newValues;
      var onChange = _this.props.onChange;
      var values = _this.state.values;
      var isActive = values.includes(value);

      if (!isActive) {
        newValues = [value];
        onChange(value);
      } else {
        return;
      }

      _this.setState({
        values: newValues
      });
    };

    return _this;
  }

  var _proto = RadioGroup.prototype;

  _proto.componentWillMount = function componentWillMount() {
    if (this.props.values) {
      this.setState({
        values: this.props.values
      });
    }
  };

  _proto.render = function render() {
    var _this2 = this;

    var _this$props = this.props,
        children = _this$props.children,
        name = _this$props.name;
    var values = this.state.values;

    var addHandlersToChildren = function addHandlersToChildren() {
      return React.Children.map(children, function (child) {
        var value = child.props.value;
        return React.cloneElement(child, {
          name: name,
          checked: values.includes(value),
          onChange: function onChange() {
            return _this2.handleToggle(value);
          }
        });
      });
    };

    return React.createElement("div", {
      className: "cui-radio-group"
    }, addHandlersToChildren());
  };

  return RadioGroup;
}(React.Component);

RadioGroup.displayName = 'RadioGroup';
RadioGroup.propTypes = {
  /**
   * optional children prop type
   */
  children: PropTypes.node,

  /**
   * Callback fired when a button is pressed, depending on whether the `type`
   * is `'radio'` or `'checkbox'`, `onChange` will be called with the value or
   * array of active values
   *
   * @controllable values
   */
  onChange: PropTypes.func,

  /**
   * An array of values, of the active (pressed) buttons
   *
   * @controllable onChange
   */
  values: PropTypes.array,

  /**
   * An HTML `<input>` name for each child button.
   *
   */
  name: PropTypes.string
};
RadioGroup.defaultProps = {
  values: [],
  onChange: function onChange() {},
  name: ''
};
export default RadioGroup;