import React, { useContext, useRef, useState } from "react";
import classnames from "classnames";
import CollapseContext from "./CollapseContext";
import { BORDER_TOP_BOTTOM } from "../utils/constant";
import { useUpdateEffect } from "../hooks";
import ConfigProviderContext from "../config-provider/ConfigProviderContext";
function validateModelValue(modelValue, accordion) {
  if (accordion && Array.isArray(modelValue)) {
    console.error('[rc-ui-lib] Collapse: "value" should not be Array in accordion mode');
    return false;
  }
  if (!accordion && !Array.isArray(modelValue)) {
    console.error('[rc-ui-lib] Collapse: "value" should be Array in non-accordion mode');
    return false;
  }
  return true;
}
const Collapse = (props) => {
  const {
    prefixCls,
    createNamespace
  } = useContext(ConfigProviderContext);
  const [bem] = createNamespace("collapse", prefixCls);
  const innerEffect = useRef(false);
  const [modelValue, setModelValue] = useState(() => {
    var _a;
    return (_a = props.value) != null ? _a : props.initValue;
  });
  const updateName = (name) => {
    var _a;
    innerEffect.current = true;
    setModelValue(name);
    (_a = props.onChange) == null ? void 0 : _a.call(props, name);
  };
  const toggle = (name, isExpanded2) => {
    const {
      accordion
    } = props;
    if (accordion) {
      updateName(name === modelValue ? "" : name);
    } else if (isExpanded2) {
      updateName(modelValue.concat(name));
    } else {
      updateName(modelValue.filter((activeName) => activeName !== name));
    }
  };
  const isExpanded = (name) => {
    const {
      accordion
    } = props;
    if (process.env.NODE_ENV !== "production" && !validateModelValue(modelValue, accordion)) {
      return false;
    }
    return accordion ? modelValue === name : modelValue.includes(name);
  };
  useUpdateEffect(() => {
    if (innerEffect.current) {
      innerEffect.current = false;
      return;
    }
    setModelValue(props.value);
  }, [props.value]);
  return /* @__PURE__ */ React.createElement(CollapseContext.Provider, {
    value: {
      isExpanded,
      toggle
    }
  }, /* @__PURE__ */ React.createElement("div", {
    className: classnames(bem(), {
      [BORDER_TOP_BOTTOM]: props.border
    })
  }, React.Children.toArray(props.children).filter(Boolean).map((child, index) => /* @__PURE__ */ React.cloneElement(child, {
    index
  }))));
};
Collapse.defaultProps = {
  border: true,
  initValue: []
};
var stdin_default = Collapse;
export {
  stdin_default as default
};
