import _defineProperty from "@babel/runtime/helpers/defineProperty";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import { createBEM } from '@zarm-design/bem';
import React, { useContext, useEffect, useState } from 'react';
import { ConfigContext } from '../config-provider';
import List from '../list';
import { RadioGroupContext } from './context';

var getValue = function getValue(props, defaultValue) {
  var _ref, _props$value;

  return (_ref = (_props$value = props.value) !== null && _props$value !== void 0 ? _props$value : props.defaultValue) !== null && _ref !== void 0 ? _ref : defaultValue;
};

var RadioGroup = function RadioGroup(props) {
  var _ref2;

  var _useState = useState(getValue(props)),
      _useState2 = _slicedToArray(_useState, 2),
      value = _useState2[0],
      setValue = _useState2[1];

  var type = props.type,
      block = props.block,
      disabled = props.disabled,
      listIconAlign = props.listIconAlign,
      compact = props.compact,
      className = props.className,
      style = props.style;

  var _useContext = useContext(ConfigContext),
      prefixCls = _useContext.prefixCls;

  var bem = createBEM('radio-group', {
    prefixCls: prefixCls
  });
  var cls = bem([(_ref2 = {}, _defineProperty(_ref2, "".concat(type), !!type), _defineProperty(_ref2, "block", block), _defineProperty(_ref2, "disabled", disabled), _defineProperty(_ref2, 'button-compact', compact), _ref2), className]);
  useEffect(function () {
    if (props.value === undefined) return;
    if (props.value === value) return;
    setValue(getValue(props));
  }, [props.value]);
  return /*#__PURE__*/React.createElement(RadioGroupContext.Provider, {
    value: {
      value: value,
      type: type,
      block: block,
      disabled: disabled,
      listIconAlign: listIconAlign,
      compact: compact,
      check: function check(v) {
        var _props$onChange;

        setValue(v);
        (_props$onChange = props.onChange) === null || _props$onChange === void 0 ? void 0 : _props$onChange.call(props, v);
      }
    }
  }, /*#__PURE__*/React.createElement("div", {
    className: cls,
    style: style
  }, /*#__PURE__*/React.createElement("div", {
    className: bem('inner')
  }, type === 'list' ? /*#__PURE__*/React.createElement(List, null, props.children) : props.children)));
};

RadioGroup.displayName = 'RadioGroup';
RadioGroup.defaultProps = {
  block: false,
  disabled: false,
  compact: false,
  listIconAlign: 'before'
};
export default RadioGroup;