import React, { forwardRef, useContext, useImperativeHandle } from "react";
import classnames from "classnames";
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 = /* @__PURE__ */ 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 : !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 ? void 0 : _a.call(props, name);
  };
  useImperativeHandle(ref, () => ({
    toggleAll
  }));
  return /* @__PURE__ */ React.createElement(CheckBoxContext.Provider, {
    value: {
      parent: {
        props
      },
      toggle,
      checked
    }
  }, /* @__PURE__ */ React.createElement("div", {
    className: classnames(bem([props.direction]))
  }, React.Children.toArray(props.children).filter(Boolean).map((child, index) => {
    var _a;
    if (((_a = child.type) == null ? void 0 : _a.displayName) !== "Checkbox")
      return child;
    return /* @__PURE__ */ React.cloneElement(child, {
      ref: setChildrenRefs(index)
    });
  })));
});
CheckBoxGroup.defaultProps = {
  defaultValue: []
};
var stdin_default = CheckBoxGroup;
export {
  stdin_default as default
};
