import React, { forwardRef, useContext, useImperativeHandle } from 'react';
import clsx from 'clsx';
import useMergedState from '../hooks/use-merged-state';
import CheckBoxContext from './CheckboxContext';
import useRefs from '../hooks/use-refs';
import ConfigProviderContext from '../config-provider/ConfigProviderContext';
var CheckBoxGroup = /*#__PURE__*/forwardRef(function (props, ref) {
  var _useContext = useContext(ConfigProviderContext),
      prefixCls = _useContext.prefixCls,
      createNamespace = _useContext.createNamespace;

  var _createNamespace = createNamespace('checkbox-group', prefixCls),
      bem = _createNamespace[0];

  var _useRefs = useRefs(),
      childrenRefs = _useRefs[0],
      setChildrenRefs = _useRefs[1];

  var _useMergedState = useMergedState({
    value: props.value,
    defaultValue: props.defaultValue
  }),
      checked = _useMergedState[0],
      setChecked = _useMergedState[1];

  var toggleAll = function toggleAll(options) {
    if (options === void 0) {
      options = {};
    }

    if (typeof options === 'boolean') {
      options = {
        checked: options
      };
    }

    var _options = options,
        isChecked = _options.checked,
        skipDisabled = _options.skipDisabled;
    var checkedChildren = childrenRefs.filter(function (item) {
      if (!item.props.bindGroup) {
        return false;
      }

      if (item.props.disabled && skipDisabled) {
        return item.checked;
      }

      return isChecked != null ? isChecked : !item.checked;
    });
    var names = checkedChildren.map(function (item) {
      return item.props.name;
    });
    setChecked(names);
    props.onChange(names);
  };

  var toggle = function toggle(name) {
    setChecked(name);
    props.onChange == null ? void 0 : props.onChange(name);
  };

  useImperativeHandle(ref, function () {
    return {
      toggleAll: toggleAll
    };
  });
  return /*#__PURE__*/React.createElement(CheckBoxContext.Provider, {
    value: {
      parent: {
        props: props
      },
      toggle: toggle,
      checked: checked
    }
  }, /*#__PURE__*/React.createElement("div", {
    className: clsx(props.className, bem([props.direction]))
  }, React.Children.toArray(props.children).filter(Boolean).map(function (child, index) {
    var _child$type;

    if (((_child$type = child.type) == null ? void 0 : _child$type.displayName) !== 'Checkbox') return child;
    return /*#__PURE__*/React.cloneElement(child, {
      ref: setChildrenRefs(index)
    });
  })));
});
CheckBoxGroup.defaultProps = {
  defaultValue: []
};
export default CheckBoxGroup;