import { jsx, jsxs } from "react/jsx-runtime";
import { forwardRef, useState, useEffect } from "react";
import { nestedMenuItemsFromObject } from "./nestedMenuItemsFromObject.js";
import { Button } from "../Button/index.js";
/* empty css                 */
import Menu$1 from "../../node_modules/@mui/material/Menu/Menu.js";
const Menu = forwardRef(
  function Menu2(props, ref) {
    const {
      options: data,
      onClick: onMenuClick = () => {
      },
      MenuProps: menuProps,
      onClose,
      iconPlacement = "left",
      withCheckbox = false,
      withActionButtons = false,
      onPrimaryButtonClick = () => {
      },
      onTertiaryButtonClick = () => {
      },
      anchorEl,
      open,
      selected,
      renderCustomHeader,
      customHeaderProps = {},
      filteredOptions,
      searchQuery,
      onSearchChange,
      onSelectAll,
      onClearSelection,
      primaryButtonProps = {},
      menuContainerClassName,
      className,
      "data-testid": dataTestId,
      ...rest
    } = props;
    const [selectedItems, setSelectedItems] = useState(
      () => customHeaderProps.selectedItems ?? []
    );
    useEffect(() => {
      if (customHeaderProps.selectedItems != null) {
        setSelectedItems(customHeaderProps.selectedItems);
      }
    }, [customHeaderProps.selectedItems]);
    const handleClose = () => {
      onClose == null ? void 0 : onClose();
    };
    const handleSelect = (opt, event) => {
      const value = opt.value;
      const newSelectedItems = value != null && selectedItems.includes(value) ? selectedItems.filter((item) => item !== value) : value != null ? [...selectedItems, value] : selectedItems;
      setSelectedItems(newSelectedItems);
      if (customHeaderProps.onSelectionChange) {
        customHeaderProps.onSelectionChange(newSelectedItems);
      }
      let itemResult;
      if (typeof opt.onClick === "function") {
        try {
          itemResult = opt.onClick(opt, event);
        } catch (e) {
          console.warn("item onClick threw:", e);
        }
      }
      if (typeof onMenuClick === "function") {
        try {
          onMenuClick(opt, newSelectedItems, itemResult);
        } catch (e) {
          console.warn("Menu onClick threw:", e);
        }
      }
    };
    const handleSelectAll = () => {
      const allValues = (filteredOptions ?? data ?? []).map((opt) => opt.value).filter((v) => v != null);
      setSelectedItems(allValues);
      onSelectAll == null ? void 0 : onSelectAll(allValues);
    };
    const handleClearSelection = () => {
      setSelectedItems([]);
      onClearSelection == null ? void 0 : onClearSelection();
    };
    const handleSearchChange = (value) => {
      onSearchChange == null ? void 0 : onSearchChange(value);
    };
    const isLoading = customHeaderProps.isLoading;
    const isSearching = customHeaderProps.isSearching;
    const hasEmptySearch = Boolean(searchQuery && (data == null ? void 0 : data.length) === 0 && !isSearching);
    const hasNoInitialData = !searchQuery && (data == null ? void 0 : data.length) === 0 && !isLoading;
    const renderLoadingState = () => /* @__PURE__ */ jsx("div", { style: { padding: "16px", textAlign: "center", color: "#666" }, children: /* @__PURE__ */ jsx("div", { children: " Loading options..." }) });
    const renderSearchingState = () => /* @__PURE__ */ jsx("div", { style: { padding: "16px", textAlign: "center", color: "#666" }, children: /* @__PURE__ */ jsx("div", { children: " Searching..." }) });
    const renderEmptySearchState = () => /* @__PURE__ */ jsx("div", { style: { padding: "16px", textAlign: "center", color: "#666" }, children: /* @__PURE__ */ jsxs("div", { children: [
      ' No results found for "',
      searchQuery,
      '"'
    ] }) });
    const renderNoDataState = () => /* @__PURE__ */ jsx("div", { style: { padding: "16px", textAlign: "center", color: "#666" }, children: /* @__PURE__ */ jsx("div", { children: "📭 No options available" }) });
    const menuItems = nestedMenuItemsFromObject({
      handleClose: onClose,
      isOpen: open,
      menuItemsData: data ?? [],
      withCheckbox,
      handleSelect,
      selectedItems,
      selected,
      ...rest
    });
    const renderHeader = () => {
      if (renderCustomHeader) {
        return renderCustomHeader({
          options: filteredOptions ?? data ?? [],
          selectedItems,
          searchQuery,
          onSearchChange: handleSearchChange,
          onSelectAll: handleSelectAll,
          onClearSelection: handleClearSelection,
          ...customHeaderProps
        });
      }
      return null;
    };
    const getMenuPositioning = () => {
      if (iconPlacement === "top") {
        return {
          anchorOrigin: { vertical: "top", horizontal: "center" },
          transformOrigin: { vertical: "bottom", horizontal: "center" }
        };
      }
      return {
        anchorOrigin: { vertical: "bottom", horizontal: "center" },
        transformOrigin: { vertical: "top", horizontal: "center" }
      };
    };
    const menuPositioning = getMenuPositioning();
    const anchorOrigin = (menuProps == null ? void 0 : menuProps.anchorOrigin) ?? menuPositioning.anchorOrigin;
    const transformOrigin = (menuProps == null ? void 0 : menuProps.transformOrigin) ?? menuPositioning.transformOrigin;
    return /* @__PURE__ */ jsx("div", { ref, ...rest, style: { display: "none" }, children: /* @__PURE__ */ jsxs(
      Menu$1,
      {
        anchorEl,
        anchorOrigin,
        className: `ia-styles ia-menu ${menuContainerClassName ?? ""} ${className ?? ""}`.trim(),
        "data-testid": dataTestId,
        id: "basic-menu",
        open,
        transformOrigin,
        onClose: handleClose,
        ...menuProps,
        children: [
          renderHeader(),
          isLoading ? renderLoadingState() : isSearching ? renderSearchingState() : hasEmptySearch ? renderEmptySearchState() : hasNoInitialData ? renderNoDataState() : /* @__PURE__ */ jsx("div", { className: "menu-scroll-area", children: menuItems }),
          withActionButtons && withCheckbox && !isLoading && !isSearching && ((data == null ? void 0 : data.length) ?? 0) > 0 && /* @__PURE__ */ jsx("div", { className: "bottom_action", children: /* @__PURE__ */ jsxs("div", { className: "ia-menu-action-button-container", children: [
            /* @__PURE__ */ jsx(Button, { variant: "tertiary", onClick: onTertiaryButtonClick, children: "Cancel" }),
            /* @__PURE__ */ jsx(
              Button,
              {
                disabled: primaryButtonProps.disabled,
                variant: "primary",
                onClick: onPrimaryButtonClick,
                children: primaryButtonProps.loading ? "Loading..." : primaryButtonProps.label ?? "Apply"
              }
            )
          ] }) })
        ]
      }
    ) });
  }
);
Menu.displayName = "Menu";
export {
  Menu
};
