import { jsx as _jsx } from "react/jsx-runtime";
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';
const CheckBoxGroup = forwardRef((props, ref) => {
  const {
    prefixCls,
    createNamespace
  } = useContext(ConfigProviderContext);
  const [bem] = createNamespace('checkbox-group', prefixCls);
  const [childrenRefs, setChildrenRefs] = useRefs();
  const [checked, setChecked] = useMergedState({
    value: props.value,
    defaultValue: props.defaultValue
  });

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

    const {
      checked: isChecked,
      skipDisabled
    } = options;
    const checkedChildren = childrenRefs.filter(item => {
      if (!item.props.bindGroup) {
        return false;
      }

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

      return isChecked !== null && isChecked !== void 0 ? isChecked : !item.checked;
    });
    const names = checkedChildren.map(item => item.props.name);
    setChecked(names);
    props.onChange(names);
  };

  const toggle = name => {
    var _a;

    setChecked(name);
    (_a = props.onChange) === null || _a === void 0 ? void 0 : _a.call(props, name);
  };

  useImperativeHandle(ref, () => ({
    toggleAll
  }));
  return _jsx(CheckBoxContext.Provider, Object.assign({
    value: {
      parent: {
        props
      },
      toggle,
      checked
    }
  }, {
    children: _jsx("div", Object.assign({
      className: clsx(props.className, bem([props.direction]))
    }, {
      children: React.Children.toArray(props.children).filter(Boolean).map((child, index) => {
        var _a;

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