import { __rest } from "tslib";
import { jsx as _jsx } from "react/jsx-runtime";
import { forwardRef, useContext, useImperativeHandle, useMemo } from 'react';
import Checker from './Checker';
import CheckBoxContext from './CheckboxContext';
import useMergedState from '../hooks/use-merged-state';
import ConfigProviderContext from '../config-provider/ConfigProviderContext';
const CheckBox = forwardRef((props, ref) => {
  const {
    prefixCls,
    createNamespace
  } = useContext(ConfigProviderContext);
  const [bem] = createNamespace('checkbox', prefixCls);

  const _a = useContext(CheckBoxContext),
        {
    parent
  } = _a,
        context = __rest(_a, ["parent"]);

  const [checked, setChecked] = useMergedState({
    value: props.checked,
    defaultValue: props.defaultChecked
  });

  const setParentValue = isChecked => {
    const {
      name
    } = props;
    const {
      max
    } = parent.props;
    const value = context.checked.slice();

    if (isChecked) {
      const overlimit = max && value.length >= max;

      if (!overlimit && value.indexOf(name) === -1) {
        value.push(name);

        if (props.bindGroup) {
          context.toggle(value);
        }
      }
    } else {
      const index = value.indexOf(name);

      if (index !== -1) {
        value.splice(index, 1);

        if (props.bindGroup) {
          context.toggle(value);
        }
      }
    }
  };

  const isChecked = useMemo(() => {
    if (parent && props.bindGroup) {
      return context.checked.indexOf(props.name) !== -1;
    }

    return checked;
  }, [context.checked, checked]);

  const toggle = (newValue = !isChecked) => {
    var _a;

    if (parent && props.bindGroup) {
      setParentValue(newValue);
    } else {
      setChecked(newValue);
      (_a = props.onChange) === null || _a === void 0 ? void 0 : _a.call(props, newValue);
    }
  };

  useImperativeHandle(ref, () => ({
    toggle,
    checked: isChecked,
    props
  }));
  return _jsx(Checker, Object.assign({}, props, {
    bem: bem,
    role: "checkbox",
    parent: parent,
    checked: isChecked,
    className: props.className,
    bindGroup: props.bindGroup,
    onToggle: toggle
  }));
});
CheckBox.displayName = 'Checkbox';
CheckBox.defaultProps = {
  bindGroup: true
};
export default CheckBox;