import { Box } from "@wix/design-system";
import React, { useContext, useState } from "react";
import { ModalServiceContext, RicosContext } from "./../../../ricos-context/index.js";
import { useBiNext } from "./../../../_shared/bi-context-provider/bi-context-provider.js";
import { unreachable } from "./../../../_shared/uncreachable.js";
import { useNodeAttrs } from "./../../../_shared/use-node-attrs.js";
import { Panel, PanelHeader } from "./../../../ui-components/index.js";
import { GALLERY_SETTINGS_MODAL_ID } from "../../consts.js";
import { SETTINGS_MODAL } from "../../data-hooks.js";
import classes from "./gallery-settings-modal-scss.js";
import { GeneralSettings } from "./general-settings/general-settings.js";
import { LayoutSettings } from "./layout-settings/layout-settings.js";
import { MediaList } from "./media-settings/media-list/media-list.js";
import { MediaSettingsForm } from "./media-settings/media-settings-form.js";
import { TabNavigation } from "./tab-navigation.js";
const GallerySettingsModal = ({
  nodeId,
  modalId,
  onFileSelect,
  activeTab: initialActiveTab,
  accept,
  _state
}) => {
  const modalService = useContext(ModalServiceContext) || {};
  const { t, isMobile } = useContext(RicosContext);
  const { pmNodeAttrs, patchPmNodeAttrs } = useNodeAttrs(nodeId, "GALLERY");
  const logBi = useBiNext({ pluginId: "gallery", modalId: GALLERY_SETTINGS_MODAL_ID, nodeId });
  const [state, setState] = useState(() => {
    if (_state) {
      return _state;
    }
    if (initialActiveTab === "design") {
      return {
        tab: "design",
        isImageSettingsOpened: false,
        selectedItemIndexes: []
      };
    }
    return {
      tab: initialActiveTab
    };
  });
  if (!pmNodeAttrs || !pmNodeAttrs.items) {
    return null;
  }
  const galleryItems = pmNodeAttrs.items.map((item, index) => ({
    ...item,
    selected: state.tab === "design" && state.selectedItemIndexes.includes(index),
    id: index.toString()
  }));
  const isImageSettingsOpened = state.tab === "design" && state.isImageSettingsOpened;
  const closeModal = () => modalService.closeModal(modalId);
  return /* @__PURE__ */ React.createElement("div", { className: classes.modal }, /* @__PURE__ */ React.createElement(
    Panel,
    {
      closeButtonProps: { onClick: closeModal },
      dataHook: SETTINGS_MODAL,
      maxHeight: isMobile ? void 0 : 630,
      onBackButtonClick: isImageSettingsOpened ? () => {
        setState((prev) => {
          return {
            ...prev,
            selectedItemIndexes: [],
            isImageSettingsOpened: false
          };
        });
      } : void 0
    },
    /* @__PURE__ */ React.createElement(
      PanelHeader,
      {
        title: t(
          isImageSettingsOpened ? "GallerySettings_Image_Settings_Header" : "GallerySettings_Header"
        ),
        className: isImageSettingsOpened ? classes.header : void 0
      }
    ),
    !(state.tab === "design" && state.isImageSettingsOpened) && /* @__PURE__ */ React.createElement(
      TabNavigation,
      {
        activeTab: state.tab,
        onTabChange: (tab) => {
          setState(() => {
            if (tab === "design") {
              return {
                tab,
                isImageSettingsOpened: false,
                selectedItemIndexes: []
              };
            }
            return { tab };
          });
        }
      }
    ),
    /* @__PURE__ */ React.createElement(
      Box,
      {
        direction: "vertical",
        padding: "SP3",
        overflowY: "auto",
        overflowX: "hidden",
        className: classes.content
      },
      (() => {
        switch (state.tab) {
          case "settings": {
            return /* @__PURE__ */ React.createElement(GeneralSettings, { nodeId, logBi });
          }
          case "layout": {
            return /* @__PURE__ */ React.createElement(LayoutSettings, { nodeId, logBi });
          }
          case "design": {
            const selectedImageIndex = galleryItems.findIndex((item) => item.selected);
            const selectedImage = galleryItems[selectedImageIndex];
            return state.isImageSettingsOpened ? /* @__PURE__ */ React.createElement(
              MediaSettingsForm,
              {
                logBi,
                closeModal,
                galleryItems,
                activeImageIndex: selectedImageIndex,
                accept,
                itemKey: `${selectedImageIndex}-${selectedImage.image?.media?.src}-${galleryItems.length}`,
                onFileSelect,
                onImageIndexChange: (next) => {
                  setState((prev) => {
                    if (prev.tab === "design") {
                      return {
                        ...prev,
                        selectedItemIndexes: [next]
                      };
                    }
                    return prev;
                  });
                },
                onDeleteClick: () => {
                  setState((prev) => {
                    if (prev.tab === "design") {
                      const activeImageIndex = prev.selectedItemIndexes[0];
                      if (activeImageIndex === void 0) {
                        throw new Error("No image selected");
                      }
                      const newSelectedIndex = galleryItems[activeImageIndex + 1] ? activeImageIndex : activeImageIndex - 1;
                      const filteredItems = galleryItems.filter(
                        (_item, index) => index !== activeImageIndex
                      );
                      patchPmNodeAttrs({ ...pmNodeAttrs, items: filteredItems });
                      return {
                        ...prev,
                        isImageSettingsOpened: newSelectedIndex !== -1,
                        selectedItemIndexes: newSelectedIndex !== -1 ? [newSelectedIndex] : []
                      };
                    }
                    return prev;
                  });
                },
                onTitleChange: (title, shouldSync) => {
                  patchPmNodeAttrs({
                    ...pmNodeAttrs,
                    items: pmNodeAttrs.items?.map((item, index) => {
                      const isCurrentItem = index === selectedImageIndex;
                      const updatedItem = {
                        ...item,
                        title: isCurrentItem ? title : item.title,
                        altText: isCurrentItem && shouldSync ? title : item.altText
                      };
                      return updatedItem;
                    })
                  });
                },
                onAltTextChange: (altText) => {
                  patchPmNodeAttrs({
                    ...pmNodeAttrs,
                    items: pmNodeAttrs.items?.map((item, index) => ({
                      ...item,
                      altText: index === selectedImageIndex ? altText : item.altText
                    }))
                  });
                },
                onLinkSave: (value) => {
                  patchPmNodeAttrs({
                    ...pmNodeAttrs,
                    items: pmNodeAttrs.items?.map((item, index) => ({
                      ...item,
                      image: item.image?.media ? {
                        ...item.image,
                        link: index === state.selectedItemIndexes[0] ? value : item.image?.link
                      } : void 0
                    }))
                  });
                },
                onUnlink: () => {
                  patchPmNodeAttrs({
                    ...pmNodeAttrs,
                    items: pmNodeAttrs.items?.map((item, index) => ({
                      ...item,
                      image: item.image?.media ? {
                        ...item.image,
                        link: index === state.selectedItemIndexes[0] ? void 0 : item.image?.link
                      } : void 0
                    }))
                  });
                }
              }
            ) : /* @__PURE__ */ React.createElement(
              MediaList,
              {
                logBi,
                galleryItems,
                onChange: ({ type, items }) => {
                  if (type === "delete" || type === "sort") {
                    patchPmNodeAttrs({
                      ...pmNodeAttrs,
                      items: items.map((item) => {
                        const { selected: _, ...rest } = item;
                        return rest;
                      })
                    });
                  }
                  setState((prev) => {
                    if (prev.tab === "design") {
                      return {
                        ...prev,
                        selectedItemIndexes: items.map((item, index) => item.selected ? index : void 0).filter((i) => i !== void 0)
                      };
                    }
                    return prev;
                  });
                },
                onFileSelect,
                onEditClick: () => {
                  setState((prev) => {
                    if (prev.tab === "design") {
                      const activeImageIndex = prev.selectedItemIndexes[0];
                      return {
                        ...prev,
                        isImageSettingsOpened: true,
                        selectedItemIndexes: [activeImageIndex]
                      };
                    }
                    return prev;
                  });
                },
                onItemDoubleClick: (imageIndex) => {
                  setState((prev) => {
                    if (prev.tab === "design") {
                      return {
                        ...prev,
                        selectedItemIndexes: [imageIndex],
                        isImageSettingsOpened: true
                      };
                    }
                    return prev;
                  });
                }
              }
            );
          }
          default:
            unreachable(state);
            return null;
        }
      })()
    )
  ));
};
export {
  GallerySettingsModal
};
//# sourceMappingURL=gallery-settings-modal.js.map
