import {
  DropdownBase,
  ListItemSection,
  SidePanel,
  listItemSectionBuilder
} from "@wix/design-system";
import Fuse from "fuse.js";
import React, {
  forwardRef,
  useContext,
  useEffect,
  useImperativeHandle,
  useMemo,
  useRef,
  useState
} from "react";
import {
  EditorContext,
  PluginsContext,
  RicosContext,
  ZIndexContext
} from "./../../../ricos-context/index.js";
import { useModalService } from "./../../../ricos-modals/modal-service-provider.js";
import { Node_Type } from "./../../../ricos-types/index.js";
import { quickActionsModalSections } from "./../../../ricos-types/plugin-types.js";
import { useBiNext } from "./../../../_shared/bi-context-provider/bi-context-provider.js";
import { ListItemDivider } from "./../../../_shared/list-item-divider/list-item-divider.js";
import { ListItemSelect } from "./../../../_shared/list-item-select/list-item-select.js";
import { UiComponentsProvider } from "./../../../ui-components/index.js";
import { QUICK_ACTIONS_ROOT } from "../data-hooks.js";
import { QUICK_ACTIONS_MODAL_ID } from "../types.js";
import styles from "./modal-scss.js";
const COMMONLY_USED = [
  "pageBreak",
  "writeWithAi",
  Node_Type.IMAGE,
  Node_Type.GALLERY,
  Node_Type.BUTTON,
  `${Node_Type.VIDEO}.youTube`
];
const QuickActionsModal = forwardRef(
  (props, ref) => {
    const { query, supportedPlugins } = props;
    const { adapter, getPublicCommands } = useContext(EditorContext);
    const plugins = useContext(PluginsContext);
    const { t, isMobile } = useContext(RicosContext);
    const zIndexService = useContext(ZIndexContext);
    const actions = useMemo(() => {
      const quickActionPlugins = plugins.getQuickActions();
      const editor = adapter.tiptapEditor;
      const filteredBySupport = supportedPlugins?.length ? quickActionPlugins.filter((action) => supportedPlugins.includes(action.id)) : quickActionPlugins;
      return filteredBySupport.filter(
        (action) => action.isVisible ? action.isVisible(editor) : true
      );
    }, [plugins, supportedPlugins, adapter]);
    const [refElement, setRefElement] = useState(null);
    const logBi = useBiNext({ modalId: QUICK_ACTIONS_MODAL_ID });
    const latestOptionsRef = useRef([]);
    const latestSelectedIdRef = useRef(void 0);
    const modalService = useModalService();
    const publicCommands = getPublicCommands();
    const options = useMemo(() => {
      const filtered = filterActions(actions, query || "", t);
      const actionsInSectionsMap = filtered.reduce(
        (groups, action) => {
          if (!query && COMMONLY_USED.includes(action.id)) {
            groups[quickActionsModalSections.CommonlyUsed] ??= [];
            groups[quickActionsModalSections.CommonlyUsed].push(action);
          }
          groups[action.section] ??= [];
          return {
            ...groups,
            [action.section]: [...groups[action.section], action]
          };
        },
        {}
      );
      actionsInSectionsMap[quickActionsModalSections.CommonlyUsed]?.sort(
        (a, b) => COMMONLY_USED.indexOf(a.id) - COMMONLY_USED.indexOf(b.id)
      );
      const quickActionOptionProps = {
        publicCommands,
        props,
        modalService,
        t,
        editor: adapter.tiptapEditor,
        logBi
      };
      const organizedOptions = !query ? Object.values(quickActionsModalSections).reduce(
        (list, section) => {
          return [
            ...list,
            ...actionsInSectionsMap[section]?.length > 0 ? createSection({
              items: actionsInSectionsMap[section],
              section,
              ...quickActionOptionProps
            }) : []
          ];
        },
        []
      ) : Object.entries(actionsInSectionsMap).reduce(
        (list, [section, items]) => {
          return [
            ...list,
            ...items.length > 0 ? createSection({
              items,
              section,
              ...quickActionOptionProps
            }) : []
          ];
        },
        []
      );
      if (organizedOptions[organizedOptions.length - 1]?.id === "-") {
        organizedOptions.pop();
      }
      return organizedOptions;
    }, [query]);
    const [selectedId, setSelectedId] = useState(
      options.find((option) => option.value === "action")?.id
    );
    const [open, setOpen] = useState(false);
    const currElement = useRef(null);
    useEffect(() => {
      setSelectedId(options.find((option) => option.value === "action")?.id);
      setOpen(!!options.length);
    }, [query]);
    useEffect(() => {
      latestOptionsRef.current = options;
      latestSelectedIdRef.current = selectedId;
    }, [options.length, query, selectedId]);
    useImperativeHandle(
      ref,
      () => ({
        onKeyDown: ({ event }) => {
          if (!latestOptionsRef.current || latestOptionsRef.current.length === 0) {
            return false;
          }
          if (["ArrowUp", "ArrowDown"].includes(event.key)) {
            const direction = event.key === "ArrowUp" ? -1 : 1;
            const activeOptions = latestOptionsRef.current.filter(
              (option) => option.value === "action"
            );
            if (!activeOptions.length) {
              return false;
            }
            setSelectedId((prev) => {
              const currIndex = activeOptions.findIndex(({ id }) => id === prev);
              const nextIndex = (currIndex + direction + activeOptions.length) % activeOptions.length;
              return activeOptions[nextIndex].id;
            });
            return true;
          }
          if (["Enter", "Tab"].includes(event.key)) {
            const option = latestOptionsRef.current.find(
              (option2) => option2.id === latestSelectedIdRef.current
            );
            if (option && "onClick" in option) {
              option?.onClick?.();
              return true;
            }
            return false;
          }
          return false;
        }
      }),
      [query, latestOptionsRef.current.length, options.length, selectedId]
    );
    if (isMobile) {
      return /* @__PURE__ */ React.createElement(
        SidePanel,
        {
          closeButtonProps: { onClick: () => modalService.closeModal(QUICK_ACTIONS_MODAL_ID) },
          width: "100%",
          maxHeight: "50vh",
          height: "fit-content"
        },
        /* @__PURE__ */ React.createElement(SidePanel.Header, { title: t("QuickActionsPlugin_Modal_Header_Title") }),
        /* @__PURE__ */ React.createElement(SidePanel.Content, { className: styles.mobileContent }, options.map((option, index) => {
          if (option.id === "-") {
            return /* @__PURE__ */ React.createElement(ListItemDivider, { key: option.id + index });
          }
          if ("optionTitle" in option && option.optionTitle) {
            return /* @__PURE__ */ React.createElement(
              ListItemSelect,
              {
                key: option.id,
                title: option.optionTitle,
                prefix: option.prefix,
                onSelect: option.onClick
              }
            );
          }
          return /* @__PURE__ */ React.createElement(ListItemSection, { key: option.id, title: t(option.id?.toString() ?? "") });
        }))
      );
    }
    return /* @__PURE__ */ React.createElement(
      "div",
      {
        className: styles.quickActionsModal,
        style: { zIndex: zIndexService.getZIndex("DIALOG") },
        ref: setRefElement
      },
      refElement && /* @__PURE__ */ React.createElement(UiComponentsProvider, { containerEl: refElement }, /* @__PURE__ */ React.createElement(
        DropdownBase,
        {
          ref: currElement,
          open,
          placement: "bottom-start",
          minWidth: 280,
          maxHeight: 250,
          className: styles.quickActionsModal,
          autoFocus: false,
          focusOnOption: selectedId,
          dataHook: QUICK_ACTIONS_ROOT,
          options,
          listType: "action"
        }
      ))
    );
  }
);
const commandToQuickActionOption = ({
  quickAction,
  publicCommands,
  props,
  editor,
  modalService,
  t,
  section,
  logBi
}) => {
  return {
    as: "button",
    dataHook: section === quickActionsModalSections.CommonlyUsed ? `${quickAction.id}${section}` : quickAction.id,
    ellipsis: false,
    id: `${quickAction.id}${section}`,
    onClick: () => {
      props?.command?.(props);
      quickAction.command({ publicCommands, editor, modalService });
      logBi({ dataHook: QUICK_ACTIONS_ROOT, value: quickAction.id });
      modalService.closeModal(QUICK_ACTIONS_MODAL_ID);
    },
    optionTitle: t(quickAction.title),
    prefixIcon: quickAction.icon ? /* @__PURE__ */ React.createElement(quickAction.icon, null) : void 0,
    prefix: quickAction.icon ? /* @__PURE__ */ React.createElement(quickAction.icon, null) : void 0,
    shouldFocusWithoutScroll: true,
    size: "small",
    title: false,
    value: "action"
  };
};
const createSection = ({
  items,
  section,
  t,
  ...rest
}) => {
  return [
    listItemSectionBuilder({
      title: t(section),
      id: section
    }),
    ...items.map(
      (item) => commandToQuickActionOption({
        quickAction: item,
        section,
        t,
        ...rest
      })
    ),
    listItemSectionBuilder({
      type: "divider",
      id: "-"
    })
  ];
};
const filterActions = (actions, query, t) => {
  if (!query) {
    return actions;
  }
  if (query.match(/^ /)?.length || (query.match(/ /gm)?.length || 0) > 1) {
    return [];
  }
  const queryIsSectionName = Object.values(quickActionsModalSections).find(
    (val) => t(val).toLowerCase() === query.toLowerCase()
  );
  if (queryIsSectionName) {
    return actions.filter(({ section }) => t(section).toLowerCase() === query.toLowerCase());
  }
  const fuse = new Fuse(actions, {
    keys: [
      { name: "title", getFn: (action) => t(action.title), weight: 0.7 },
      { name: "section", getFn: (action) => t(action.section), weight: 0.3 },
      { name: "tags", getFn: (action) => action.tags.join(" "), weight: 0.2 }
    ],
    threshold: 0.4,
    minMatchCharLength: query.length > 1 ? 2 : 1
  });
  const result = fuse.search(query);
  if (result.length) {
    return result.map(({ item }) => item);
  }
  return actions.filter((item) => t(item.title).toLowerCase().includes(query.toLowerCase()));
};
export {
  QuickActionsModal
};
//# sourceMappingURL=modal.js.map
