import { Box, Button, Loader, Search, SectionHelper, SidePanel } from "@wix/design-system";
import lodash from "lodash";
import React, { useContext, useEffect, useState } from "react";
import {
  EditorContext,
  ModalServiceContext,
  PluginsEventsContext,
  RicosContext
} from "./../../ricos-context/index.js";
import { useBiNext } from "./../../_shared/bi-context-provider/bi-context-provider.js";
import { unreachable } from "./../../_shared/uncreachable.js";
import { MEDIA_POPOVERS_BUTTONS_NAMES_BI, uuid } from "./../../wix-rich-content-common/index.js";
import {
  getLowerCaseAppEmbedType,
  isTypeAppEmbed,
  toAppEmbedData
} from "./../utils.js";
import {
  FooterActions,
  Panel,
  PanelHeader,
  usePanelContainerElement
} from "./../../ui-components/index.js";
import { contentTypeMap } from "../constants.js";
import {
  INSERT_VERTICAL_EMBED_CANCEL_BUTTON,
  INSERT_VERTICAL_EMBED_FOOTER_ACTIONS,
  INSERT_VERTICAL_EMBED_ITEMS_LIST,
  INSERT_VERTICAL_EMBED_MODAL,
  INSERT_VERTICAL_EMBED_SEARCH_INPUT
} from "../data-hooks.js";
import { useVerticalEmbedRequestService } from "../services/fetch-vertical-embed-data.js";
import { ItemsList } from "../toolbar/items-list.js";
import { VERTICAL_EMBED_TYPE } from "../types.js";
const InsertModal = ({ componentData, nodeId, modalId }) => {
  const { t, isMobile } = useContext(RicosContext);
  const { getPublicCommands } = useContext(EditorContext);
  const modalService = useContext(ModalServiceContext) || {};
  const pluginsEvents = useContext(PluginsEventsContext);
  const { fetchVerticalEmbedItems } = useVerticalEmbedRequestService();
  const logBi = useBiNext({ modalId, pluginId: "verticalEmbed", nodeId });
  const containerEl = usePanelContainerElement();
  const contentType = contentTypeMap[componentData.type];
  const [state, setState] = useState({
    status: "LOADING",
    searchText: "",
    requestId: uuid()
  });
  useEffect(() => {
    fetchEmbedItems("");
  }, []);
  const fetchEmbedItems = lodash.debounce((inputString = "") => {
    const requestId = uuid();
    setState(() => ({
      status: "LOADING",
      searchText: inputString,
      requestId
    }));
    (async () => {
      try {
        const verticalApiType = getLowerCaseAppEmbedType(componentData.type);
        const items = isTypeAppEmbed(componentData.type) ? await fetchVerticalEmbedItems(verticalApiType, inputString) : [];
        setState((prev) => {
          if (prev.status === "LOADING" && prev.requestId !== requestId) {
            return prev;
          }
          return {
            status: "READY",
            items: items ?? [],
            selectedItem: void 0,
            searchText: inputString,
            showSelectionError: false
          };
        });
      } catch (e) {
        console.error("Failed to load products", e);
        setState((prev) => {
          if (prev.status === "LOADING" && prev.requestId !== requestId) {
            return prev;
          }
          return {
            status: "READY",
            items: [],
            selectedItem: void 0,
            searchText: inputString,
            showSelectionError: false
          };
        });
      }
    })();
  }, 300);
  const closeModal = () => modalService.closeModal(modalId);
  const onSave = () => {
    pluginsEvents.publishPluginPopoverClick?.({
      pluginId: VERTICAL_EMBED_TYPE,
      buttonName: MEDIA_POPOVERS_BUTTONS_NAMES_BI.embed
    });
    if (state.status !== "READY" || !state.selectedItem) {
      setState((prev) => ({ ...prev, showSelectionError: true }));
      return;
    }
    const embedData = toAppEmbedData(state.selectedItem, componentData, t);
    insertEmbedNode(embedData);
    closeModal();
  };
  const insertEmbedNode = (verticalEmbed) => {
    const publicCommands = getPublicCommands();
    setTimeout(
      () => nodeId ? publicCommands?.setBlock(nodeId, VERTICAL_EMBED_TYPE, {
        ...verticalEmbed,
        error: false,
        loading: false
      }) : publicCommands?.insertBlockWithBlankLines(VERTICAL_EMBED_TYPE, verticalEmbed),
      50
    );
    closeModal();
  };
  if (!componentData) {
    return null;
  }
  return /* @__PURE__ */ React.createElement(
    Panel,
    {
      height: isMobile ? "100%" : "540px",
      closeButtonProps: { onClick: closeModal },
      dataHook: INSERT_VERTICAL_EMBED_MODAL
    },
    /* @__PURE__ */ React.createElement(PanelHeader, { title: t(`Embed_Vertical_${contentType}_Title`) }),
    /* @__PURE__ */ React.createElement(Box, { padding: "SP3" }, /* @__PURE__ */ React.createElement(
      Search,
      {
        size: "small",
        value: state.searchText,
        onChange: (e) => {
          fetchEmbedItems(e.target.value);
          logBi({
            dataHook: INSERT_VERTICAL_EMBED_SEARCH_INPUT,
            value: e.target.value
          });
        },
        onClear: () => fetchEmbedItems(""),
        placeholder: t(`Embed_Vertical_${contentType}_Search_Placeholder`),
        dataHook: INSERT_VERTICAL_EMBED_SEARCH_INPUT
      }
    )),
    (() => {
      switch (state.status) {
        case "LOADING":
          return /* @__PURE__ */ React.createElement(Box, { align: "center", verticalAlign: "middle", height: "252px" }, /* @__PURE__ */ React.createElement(Loader, null));
        case "READY":
          return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(Box, { direction: "vertical", paddingBottom: "SP3", overflow: "auto" }, /* @__PURE__ */ React.createElement(
            ItemsList,
            {
              selectedItem: state.selectedItem,
              items: state.items,
              hasActiveSearch: state.searchText.length > 0,
              onClick: (item) => {
                logBi({
                  dataHook: INSERT_VERTICAL_EMBED_ITEMS_LIST,
                  value: contentType
                });
                setState((prev) => {
                  if (prev.status === "READY") {
                    return {
                      ...prev,
                      showSelectionError: false,
                      selectedItem: item.id === prev.selectedItem?.id ? void 0 : item
                    };
                  }
                  return prev;
                });
              },
              contentType,
              modalRef: containerEl
            }
          )), state.showSelectionError && /* @__PURE__ */ React.createElement(Box, { padding: "SP3", position: "absolute", bottom: "40px" }, /* @__PURE__ */ React.createElement(
            SectionHelper,
            {
              appearance: "danger",
              title: t("Embed_Vertical_Nothing_Selected_Error_Title"),
              showCloseButton: true,
              onClose: () => setState((prev) => ({ ...prev, showSelectionError: false }))
            },
            t("Embed_Vertical_Nothing_Selected_Error_Description")
          )));
        default:
          unreachable(state);
          return null;
      }
    })(),
    /* @__PURE__ */ React.createElement(SidePanel.Footer, { showDivider: true }, state.status === "READY" && state.items.length === 0 && state.searchText.length === 0 ? /* @__PURE__ */ React.createElement(Box, { align: "right", gap: "SP2" }, /* @__PURE__ */ React.createElement(
      Button,
      {
        onClick: () => {
          logBi({
            dataHook: INSERT_VERTICAL_EMBED_CANCEL_BUTTON
          });
          closeModal();
        },
        priority: "primary",
        dataHook: INSERT_VERTICAL_EMBED_CANCEL_BUTTON,
        size: "small"
      },
      t("Embed_Vertical_Close_Button")
    )) : /* @__PURE__ */ React.createElement(
      FooterActions,
      {
        dataHook: INSERT_VERTICAL_EMBED_FOOTER_ACTIONS,
        onCancel: closeModal,
        logBi,
        onSave,
        saveButtonLabel: t("Embed_Vertical_Add_Button")
      }
    ))
  );
};
export {
  InsertModal
};
//# sourceMappingURL=insert-modal.js.map
