import { jsx, jsxs, Fragment } from "react/jsx-runtime";
import { useState, useRef, useEffect } from "react";
import { components } from "react-select";
import { FixedSizeList } from "react-window";
import { Loader } from "../Loader/index.js";
const MenuList = (props) => {
  const { options, children, maxHeight, selectProps } = props;
  const { isLoading } = selectProps;
  const itemHeight = 37;
  const [dynamicHeight, setDynamicHeight] = useState(
    Math.min(options.length * itemHeight, maxHeight)
  );
  const listRef = useRef(null);
  useEffect(() => {
    const newHeight = Math.min(options.length * itemHeight, maxHeight);
    setDynamicHeight(newHeight);
  }, [options, maxHeight]);
  const handleScroll = ({
    scrollOffset,
    scrollUpdateWasRequested
  }) => {
    if (!listRef.current || scrollUpdateWasRequested) return;
    const totalHeight = options.length * itemHeight;
    if (scrollOffset + dynamicHeight >= totalHeight - 2) {
      if (typeof selectProps.onMenuScrollToBottom === "function") {
        selectProps.onMenuScrollToBottom();
      }
    }
  };
  if (isLoading) {
    return /* @__PURE__ */ jsx(components.MenuList, { className: "menulistScroll", ...props, children: /* @__PURE__ */ jsx("div", { className: "ia-select-loading-container", children: /* @__PURE__ */ jsx(Loader, { size: "small" }) }) });
  }
  if (options.length === 0) {
    return /* @__PURE__ */ jsx(components.MenuList, { className: "menulistScroll", ...props, children: /* @__PURE__ */ jsx("div", { className: "ia-select-no-options-message", children: selectProps.noOptionMessage }) });
  }
  const childrenArr = Array.isArray(children) ? children : [];
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(components.MenuList, { className: "menulistScroll", ...props, children: /* @__PURE__ */ jsx(
      FixedSizeList,
      {
        ref: listRef,
        height: dynamicHeight,
        itemCount: options.length,
        itemSize: itemHeight,
        width: "100%",
        onScroll: handleScroll,
        children: ({ index, style }) => /* @__PURE__ */ jsx("div", { style, children: childrenArr[index] })
      }
    ) }),
    selectProps.maxSelectableOptions !== void 0 && options.length > 0 && /* @__PURE__ */ jsx("span", { className: "ia-select-max-selectable-options", children: `Maximum ${selectProps.maxSelectableOptions} selections` })
  ] });
};
export {
  MenuList
};
