import { Col, Dropdown, Menu, Row } from "antd";
import classNames from "classnames";
import ShopifyModal from "components/ShopifyModal";
import ShopifyStoreDomainInputModal from "components/ShopifyStoreDomainInputModal";
import { Paragraph, Text } from "components/Typography";
import { SEGMENT_EVENTS } from "constants/segment";
import { useAnalytics } from "hooks/useAnalytics";
import { useModules } from "hooks/useModules";
import { TipsLinkItem } from "models/talent/talent-profile-module.model";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { v4 as uuidv4 } from "uuid";
import {
  FLAGS,
  IfFeatureDisabled,
  IfFeatureEnabled,
  useFeatureIsOn,
} from "@komi-app/flags-sdk";
import { useDispatch } from "react-redux";
import { useTypedSelector } from "redux/rootReducer";
import { triggerCheckCollectionAction } from "redux/Shopify/actions";
import { selectShopifyStores } from "redux/Shopify/selector";
import { setActiveModuleAction } from "redux/Talent/actions";
import { selectLocalizationSelected } from "redux/User/selector";
import { MODAL_STEPS } from "redux/Shopify/types";
import BandsintownEditorModal from "../../../components/BandsintownEditorModal";
import SeatedEditorModal from "../../../components/SeatedEditorModal";
import "./AddModule.scss";
import ShopMyShelfEditorModal from "components/ShopMyShelfEditorModal";
import ShopListEditorModal from "components/ShopListEditorModal";
import DataCaptureAudienceModal from "components/DataCaptureAudience/DataCaptureCreationModal";
import { DCAFormStepsProps } from "components/DataCaptureAudience/CreationModalForms/schemas";
import { dcaFormValuesToItem } from "components/DataCaptureAudience/dca-item-mapping-fns";

import { Icon as TalentIcon } from "components/Icon";
import RyeShopifyModal from "components/RyeShopifyModal";
import { RYE_MODAL_STEPS } from "redux/RyeShopify/types";
import RyeShopifyStoreDomainInputModal from "components/RyeShopifyStoreDomainInputModal/RyeShopifyStoreDomainInputModal";
import { selectRyeShopifyStores } from "redux/RyeShopify/selector";
import { triggerRyeCheckCollectionAction } from "redux/RyeShopify/actions";
import { getMenuItems } from "./get-menu-items";
import { getMenuItemsUpdated } from "./get-menu-items-updated";
import { Icon } from "@komi-app/components";
import { useWindowSize } from "../../../hooks";
import ThroneLinkModal from "components/ThroneLinkModal";
import { useAudienceAndCampaignFeatureOn } from "../../../hooks/useAudienceAndCampaignMobileBlock";
import { ModuleCreationModals } from "../ModuleCreationModals/ModuleCreationModals";
import { useHistory } from "react-router-dom";
import TipsLinkModal from "../../../components/TipsLinkModal";
import { ModuleType } from "@komi-app/shared-types";
import { useCreatorTracking, CreatorEvent } from "@komi-app/analytics-sdk";
import { DEFAULT_UUID } from "@komi-app/profiles-sdk";
import { trackingProps } from "utils/tracking";

interface AddModuleProps {
  isSolid?: boolean;
  groupId?: string;

  /**
   * Show menu
   * If passed, will be controlled by parent else will be controlled by internal state
   * @default undefined
   */
  showMenu?: boolean;
  setShowMenu?: (value: boolean) => void;
}

interface ControlledAddModuleProps {
  isSolid?: boolean;
  groupId?: string;
  showMenu: boolean;
  setShowMenu: (value: boolean) => void;
}

const AddModule: React.FC<AddModuleProps> = ({
  isSolid = true,
  groupId,
  showMenu: propShowMenu,
  setShowMenu: propSetShowMenu,
}) => {
  const [internalShowMenu, setInternalShowMenu] = useState(false);

  const showMenu = propShowMenu ?? internalShowMenu;
  const setShowMenu =
    propShowMenu !== undefined ? propSetShowMenu : setInternalShowMenu;

  return (
    <ControlledAddModule
      isSolid={isSolid}
      groupId={groupId}
      showMenu={showMenu}
      setShowMenu={setShowMenu || (() => {})}
    />
  );
};

const ControlledAddModule: React.FC<ControlledAddModuleProps> = ({
  isSolid = true,
  groupId,
  showMenu,
  setShowMenu,
}) => {
  const dispatch = useDispatch();
  const { modules, setModuleList } = useModules();
  const [showShopifyInputModal, setShowShopifyInputModal] = useState(false);
  const [visibleShopifyModal, setVisibleShopifyModal] = useState(false);
  const [step, setStep] = useState<MODAL_STEPS>(MODAL_STEPS.LOGIN);
  const [showRyeShopifyInputModal, setShowRyeShopifyInputModal] =
    useState(false);
  const [visibleRyeShopifyModal, setVisibleRyeShopifyModal] = useState(false);
  const [ryeStep, setRyeStep] = useState<RYE_MODAL_STEPS>(
    RYE_MODAL_STEPS.LOGIN
  );
  const [visibleBandsintown, setVisibleBandsintown] = useState(false);
  const [visibleSeated, setVisibleSeated] = useState(false);
  const [visibleShopMyShelf, setVisibleShopMyShelf] = useState(false);
  const [visibleShopList, setVisibleShopList] = useState(false);
  const [visibleThroneLink, setVisibleThroneLink] = useState(false);
  const [visibleTipsLink, setVisibleTipsLink] = useState(false);
  const [dataCaptureModalVisible, setDataCaptureModalVisible] = useState(false);
  const [dataCaptureCreationType, setDataCaptureCreationType] = useState<
    | ModuleType.DATA_CAPTURE_COUPON_CODE
    | ModuleType.DATA_CAPTURE_SECRET_LINK
    | ModuleType.DATA_CAPTURE_SIGNUP
  >();
  const localizationSelected = useTypedSelector(selectLocalizationSelected);
  const [openKeys, setOpenKeys] = useState<string[]>([]);
  const stores = useTypedSelector(selectShopifyStores);
  const ryeStores = useTypedSelector(selectRyeShopifyStores);
  const handleScroll = useCallback(() => {
    showMenu && setShowMenu(false);
    setOpenKeys([]);
  }, [showMenu, setShowMenu]);

  const { sendSegmentEvent } = useAnalytics();
  const history = useHistory();
  const isContentMenuEnabled = useFeatureIsOn(FLAGS.FEAT_SB_389_ADD_ITEM_MENU);
  const isNewYoutube = useFeatureIsOn(FLAGS.NEW_YOUTUBE);
  const isNewPodcast = useFeatureIsOn(FLAGS.NEW_PODCAST);
  const isShopifyOn = useFeatureIsOn(FLAGS.SHOPIFY);
  const isRyeShopifyOn = useFeatureIsOn(FLAGS.RYE);
  const useTiers = useAudienceAndCampaignFeatureOn(FLAGS.USE_TIERS_TALENT);
  const isAudiencesAndCampaignsOn =
    useAudienceAndCampaignFeatureOn(FLAGS.DCA) || useTiers;
  const isNewAddModuleMenuOn = useFeatureIsOn(
    FLAGS.GS_130_UPDATE_ADD_MODULES_MENU
  );
  const isThroneOn = useFeatureIsOn(FLAGS.FEAT_SB_263_THRONE_LINK_MODULE);
  const isTikTokOn = useFeatureIsOn(FLAGS.FEAT_SB_390_TIKTOK_MODULE);
  const isTipsModuleOn =
    useFeatureIsOn(FLAGS.FEAT_SB_634_DONATION_MODULES) || true;
  const useAnalyticsSDK = useFeatureIsOn(FLAGS.USE_ANALYTICS_SDK_TALENT);
  const { createTracker } = useCreatorTracking();
  const moduleCreated = createTracker(CreatorEvent.MODULE_CREATED);
  const elementCreated = createTracker(CreatorEvent.ELEMENT_CREATED);
  const openModuleCreationMenu = createTracker(
    CreatorEvent.OPEN_MODULE_CREATION_MENU
  );
  const shopifyConnectionFlowCompleted = createTracker(
    CreatorEvent.SHOPIFY_CONNECTION_FLOW_COMPLETED
  );

  const { height } = useWindowSize();

  const buttonText = isContentMenuEnabled ? "Add Content" : "Add New Module";

  useEffect(() => {
    if (showMenu) {
      window.addEventListener("scroll", handleScroll);
      return () => window.removeEventListener("scroll", handleScroll);
    }
  }, [showMenu]);
  const onAddNewModule = useCallback(
    (type: ModuleType, data?: any) => {
      const newModule = {
        id: uuidv4(), // TODO: set from backend
        order: 0,
        name: "New Module",
        type: type,
        items: [],
        expand: true,
        isEdit: true,
        isCreate: true,
        isLoading: false,
        groupId,
        showTitle: true,
        ...data,
      };

      const list =
        modules?.map((module: any) => {
          return { ...module, order: module.order + 1 };
        }) || [];
      if (groupId) {
        const module = list.find((item: any) => item.id === groupId);
        if (module) {
          module.items = [newModule, ...module.items].map((el, index) => ({
            ...el,
            order: index,
          }));
        }
        setModuleList?.(list);
        return;
      }

      setModuleList?.([newModule, ...list]);
      dispatch(setActiveModuleAction(newModule.id));

      window.scrollTo({
        behavior: "smooth",
        top: 0,
      });
    },
    [modules, groupId, setModuleList]
  );

  // lets ShopifyModule know that it has to check collection
  const callbackAddShopifyModule = useCallback(() => {
    onAddNewModule(ModuleType.SHOPIFY);
    dispatch(triggerCheckCollectionAction(true));
    setVisibleShopifyModal(false);
  }, [dispatch, modules, onAddNewModule]);

  const handleLoginCallback = () => {
    setVisibleShopifyModal(false);
    setShowShopifyInputModal(true);
  };

  const callbackAddRyeShopifyModule = useCallback(() => {
    onAddNewModule(ModuleType.RYE_SHOPIFY);
    dispatch(triggerRyeCheckCollectionAction(true));
    setVisibleRyeShopifyModal(false);
  }, [dispatch, modules, onAddNewModule]);

  const handleRyeLoginCallback = () => {
    setVisibleRyeShopifyModal(false);
    setShowRyeShopifyInputModal(true);
  };

  const onAddModule = useCallback(
    (menu: any) => () => {
      setShowMenu(false);

      if (menu.type === ModuleType.SHOPIFY) {
        if (!stores.length) {
          // set login step for new connection
          step !== MODAL_STEPS.LOGIN && setStep(MODAL_STEPS.LOGIN);
          setVisibleShopifyModal(true);
          return;
        }
      }
      if (menu.type === ModuleType.RYE_SHOPIFY) {
        if (!ryeStores.length) {
          // set login step for new connection
          ryeStep !== RYE_MODAL_STEPS.LOGIN &&
            setRyeStep(RYE_MODAL_STEPS.LOGIN);
          setVisibleRyeShopifyModal(true);
          return;
        }
      }

      if (menu.type === ModuleType.BANDSINTOWN) {
        setTimeout(() => {
          setVisibleBandsintown(true);
        }, 150);
        return;
      }
      if (menu.type === ModuleType.SEATED) {
        setTimeout(() => {
          setVisibleSeated(true);
        }, 150);
        return;
      }
      if (menu.type === ModuleType.SHOP_MY_SHELF) {
        setTimeout(() => {
          setVisibleShopMyShelf(true);
        }, 150);
        return;
      }
      if (menu.type === ModuleType.SHOP_LIST) {
        setTimeout(() => {
          setVisibleShopList(true);
        }, 150);
        return;
      }
      if (
        menu.type === ModuleType.DATA_CAPTURE_COUPON_CODE ||
        menu.type === ModuleType.DATA_CAPTURE_SECRET_LINK ||
        menu.type === ModuleType.DATA_CAPTURE_SIGNUP
      ) {
        setDataCaptureCreationType(menu.type);
        setTimeout(() => {
          setDataCaptureModalVisible(true);
        }, 150);
        return;
      }
      if (menu.type === ModuleType.THRONE_LINK) {
        setTimeout(() => {
          setVisibleThroneLink(true);
        }, 150);
        return;
      }

      if (
        menu.type === ModuleType.PAYPAL_LINK ||
        menu.type === ModuleType.VENMO_LINK ||
        menu.type === ModuleType.CASHAPP_LINK ||
        menu.type === ModuleType.PATREON_LINK
      ) {
        setTimeout(() => {
          setVisibleTipsLink(true);
        }, 150);
        return;
      }

      const { pageId, pageName, type } = trackingProps(
        menu.type === ModuleType.EVENTS ? "CUSTOM EVENT" : menu.type,
        localizationSelected
      );

      useAnalyticsSDK
        ? moduleCreated({
            pageId,
            pageName,
            type,
          })
        : sendSegmentEvent(SEGMENT_EVENTS.MODULDE_CREATED, {
            "Module Type": type,
            "Page ID": pageId,
            "Page Name": pageName,
          });

      // settimeout for nice behavior
      setTimeout(() => {
        onAddNewModule(menu.type);
      }, 150);
    },
    [
      localizationSelected,
      modules,
      stores,
      ryeStores,
      step,
      groupId,
      onAddNewModule,
      sendSegmentEvent,
    ]
  );

  const handleAddBandsintown = useCallback(
    (values) => {
      setVisibleBandsintown(false);

      const { pageId, pageName, type } = trackingProps(
        ModuleType.BANDSINTOWN,
        localizationSelected
      );

      if (useAnalyticsSDK) {
        moduleCreated({ pageId, pageName, type });
        elementCreated({ pageId, pageName, type });
      } else {
        sendSegmentEvent(SEGMENT_EVENTS.MODULDE_CREATED, {
          "Module Type": type,
          "Page ID": pageId,
          "Page Name": pageName,
        });
        sendSegmentEvent(SEGMENT_EVENTS.ELEMENT_CREATED, {
          "Module Type": "BANDSINTOWN EVENT", // FIXME
          "Page ID": pageId,
          "Page Name": pageName,
        });
      }
      onAddNewModule(ModuleType.BANDSINTOWN, {
        items: [{ ...values, order: 0 }],
      });
    },
    [localizationSelected, onAddNewModule, sendSegmentEvent]
  );
  const handleAddSeated = useCallback(
    (values) => {
      setVisibleBandsintown(false);

      const { pageId, pageName, type } = trackingProps(
        ModuleType.SEATED,
        localizationSelected
      );

      if (useAnalyticsSDK) {
        moduleCreated({ pageId, pageName, type });
        elementCreated({ pageId, pageName, type });
      } else {
        sendSegmentEvent(SEGMENT_EVENTS.MODULDE_CREATED, {
          "Module Type": type,
          "Page ID": pageId,
          "Page Name": pageName,
        });
        sendSegmentEvent(SEGMENT_EVENTS.ELEMENT_CREATED, {
          "Module Type": "SEATED EVENT",
          "Page ID": pageId,
          "Page Name": pageName,
        });
      }

      onAddNewModule(ModuleType.SEATED, {
        items: [{ ...values, order: 0 }],
      });
    },
    [localizationSelected, onAddNewModule, sendSegmentEvent]
  );
  const handleShopMyShelf = useCallback(
    (values) => {
      setVisibleShopMyShelf(false);

      const { pageId, pageName, type } = trackingProps(
        "SHOPMYSHELF",
        localizationSelected
      );

      if (useAnalyticsSDK) {
        moduleCreated({ pageId, pageName, type });
        elementCreated({ pageId, pageName, type });
      } else {
        sendSegmentEvent(SEGMENT_EVENTS.MODULDE_CREATED, {
          "Module Type": type,
          "Page ID": pageId,
          "Page Name": pageName,
        });
        sendSegmentEvent(SEGMENT_EVENTS.ELEMENT_CREATED, {
          "Module Type": type,
          "Page ID": pageId,
          "Page Name": pageName,
        });
      }

      onAddNewModule(ModuleType.SHOP_MY_SHELF, {
        name: values.name || "New Module",
        items: [{ url: values.url, order: 0 }],
      });
    },
    [localizationSelected, onAddNewModule, sendSegmentEvent]
  );
  const handleShopList = useCallback(
    (values) => {
      setVisibleShopList(false);

      const { pageId, pageName, type } = trackingProps(
        "SHOPLIST",
        localizationSelected
      );

      if (useAnalyticsSDK) {
        moduleCreated({ pageId, pageName, type });
        elementCreated({ pageId, pageName, type });
      } else {
        sendSegmentEvent(SEGMENT_EVENTS.MODULDE_CREATED, {
          "Module Type": type,
          "Page ID": pageId,
          "Page Name": pageName,
        });
        sendSegmentEvent(SEGMENT_EVENTS.ELEMENT_CREATED, {
          "Module Type": type,
          "Page ID": pageId,
          "Page Name": pageName,
        });
      }

      onAddNewModule(ModuleType.SHOP_LIST, {
        name: values.name || "New Module",
        items: [{ url: values.url, order: 0 }],
      });
    },
    [localizationSelected, onAddNewModule, sendSegmentEvent]
  );
  const handleDataCaptureFormCreated = useCallback(
    (values: DCAFormStepsProps) => {
      setDataCaptureModalVisible(false);

      if (!values.type) {
        console.log("No creation type specified");
        return;
      }

      const newModule = dcaFormValuesToItem(values, {
        name: "New Module",
        order: 0,
      });
      onAddNewModule(newModule.type, {
        name: newModule.name,
        items: [newModule],
      });
    },
    [localizationSelected, onAddNewModule, sendSegmentEvent]
  );
  const handleThroneLink = useCallback(
    (url) => {
      const { pageId, pageName, type } = trackingProps(
        ModuleType.THRONE_LINK,
        localizationSelected
      );

      if (useAnalyticsSDK) {
        moduleCreated({ pageId, pageName, type });
        elementCreated({ pageId, pageName, type });
      } else {
        sendSegmentEvent(SEGMENT_EVENTS.MODULDE_CREATED, {
          "Module Type": type,
          "Page ID": pageId,
          "Page Name": pageName,
        });
        sendSegmentEvent(SEGMENT_EVENTS.ELEMENT_CREATED, {
          "Module Type": type,
          "Page ID": pageId,
          "Page Name": pageName,
        });
      }

      setVisibleThroneLink(false);
      onAddNewModule(ModuleType.LINK, {
        name: "Throne",
        items: [
          {
            url,
            title: "My Throne Wishlist",
            thumbnail:
              "https://komi-production-assets.s3-accelerate.amazonaws.com/photos/-W1BJQRavoGWC8VlU_qTU.png",
          },
        ],
      });
    },
    [onAddNewModule, sendSegmentEvent]
  );

  const handleTipsLink = useCallback(
    ({ src, title, url, platform }: TipsLinkItem) => {
      const { pageId, pageName, type } = trackingProps(
        `${platform} LINK`,
        localizationSelected
      );

      if (useAnalyticsSDK) {
        moduleCreated({ pageId, pageName, type });
        elementCreated({ pageId, pageName, type });
      } else {
        sendSegmentEvent(SEGMENT_EVENTS.MODULDE_CREATED, {
          "Module Type": platform,
          "Page ID": pageId,
          "Page Name": pageName,
        });
        sendSegmentEvent(SEGMENT_EVENTS.ELEMENT_CREATED, {
          "Module Type": `${platform} LINK`,
          "Page ID": pageId,
          "Page Name": pageName,
        });
      }

      setVisibleTipsLink(false);
      onAddNewModule(ModuleType.LINK, {
        name: "Tips",
        items: [
          {
            url,
            title,
            thumbnail: src,
            visible: true,
          },
        ],
      });
    },
    [onAddNewModule, sendSegmentEvent]
  );

  const menu = useMemo(() => {
    if (isNewAddModuleMenuOn) {
      return (
        <Menu
          openKeys={openKeys}
          onOpenChange={(data) => {
            setOpenKeys(data);
          }}
          expandIcon={
            <>
              <div className="m__l--16 flex flex-col min-h-full justify__content--center">
                <Icon
                  width={24}
                  height={24}
                  style={{ minWidth: 24, minHeight: 24 }}
                  name="arrow/right"
                />
              </div>
            </>
          }
          data-tour="onboarding-module-menu"
          className={classNames("add_module__menu")}
          style={{ width: "100%", maxWidth: "390px" }}
          triggerSubMenuAction={"click"}
        >
          {getMenuItemsUpdated(stores, ryeStores, {
            isNewPodcast,
            isNewYoutube,
            isShopifyOn,
            isRyeShopifyOn,
            isAudiencesAndCampaignsOn,
            isThroneOn,
            isTikTokOn,
          })?.map((item, index) => {
            if (!item.subMenu) {
              return (
                <Menu.Item
                  data-testid={item.testId}
                  key={index}
                  onClick={onAddModule(item)}
                >
                  <div className="m__r--16 flex flex-row align__items--center">
                    <div className="height--24">{item.icon}</div>
                    <div className="m__l--16">
                      <Paragraph preset="semibold16">{item.title}</Paragraph>
                      {item.description && (
                        <Paragraph
                          preset="regular12"
                          className="text--tundola"
                          style={{ whiteSpace: "break-spaces" }}
                        >
                          {item.description}
                        </Paragraph>
                      )}
                    </div>
                  </div>
                </Menu.Item>
              );
            }
            return (
              <Menu.SubMenu
                data-testid={item.testId}
                popupClassName={classNames("add-module__sub-menu")}
                key={index}
                title={
                  <div>
                    <Paragraph preset="semibold16">{item.title}</Paragraph>
                    {item.description && (
                      <Paragraph
                        preset="regular12"
                        className="text--tundola"
                        style={{ whiteSpace: "break-spaces" }}
                      >
                        {item.description}
                      </Paragraph>
                    )}
                  </div>
                }
                icon={
                  <div className="m__r--16 flex flex-col min-h-full justify__content--center">
                    <div className="height--24">{item.icon}</div>
                  </div>
                }
              >
                {item.subMenu.map((el: any, index) => (
                  <React.Fragment key={index}>
                    {el.type !== "ON_DEMAND_VIDEO" ? (
                      <Menu.Item onClick={onAddModule(el)}>
                        <Row gutter={8} align="middle">
                          <Col className="height--24">{el.icon}</Col>
                          <Col>
                            <Paragraph preset="semibold16">
                              {el.title}
                            </Paragraph>
                          </Col>
                        </Row>
                      </Menu.Item>
                    ) : (
                      <></>
                    )}
                  </React.Fragment>
                ))}
              </Menu.SubMenu>
            );
          })}
        </Menu>
      );
    }

    return (
      <Menu
        openKeys={openKeys}
        onOpenChange={(data) => {
          setOpenKeys(data);
        }}
        data-tour="onboarding-module-menu"
        className={classNames("add_module__menu")}
        style={{ width: 285 }}
        triggerSubMenuAction={"click"}
      >
        {getMenuItems(stores, ryeStores, {
          isNewPodcast,
          isNewYoutube,
          isShopifyOn,
          isRyeShopifyOn,
          isAudiencesAndCampaignsOn,
        })?.map((item, index) => {
          if (!item.subMenu) {
            return (
              <Menu.Item
                data-testid={item.testId}
                key={index}
                onClick={onAddModule(item)}
              >
                <Row gutter={8} align="middle">
                  <Col className="height--24">{item.icon}</Col>
                  <Col>
                    <Paragraph preset="semibold16">{item.title}</Paragraph>
                  </Col>
                </Row>
              </Menu.Item>
            );
          }
          return (
            <Menu.SubMenu
              data-testid={item.testId}
              popupClassName={classNames("add-module__sub-menu")}
              key={index}
              title={item.title}
              icon={<div className="height--24 m__r--16">{item.icon}</div>}
            >
              {item.subMenu.map((el: any, index) => (
                <React.Fragment key={index}>
                  {el.type !== "ON_DEMAND_VIDEO" ? (
                    <Menu.Item onClick={onAddModule(el)}>
                      <Row gutter={8} align="middle">
                        <Col className="height--24">{el.icon}</Col>
                        <Col>
                          <Paragraph preset="semibold16">{el.title}</Paragraph>
                        </Col>
                      </Row>
                    </Menu.Item>
                  ) : (
                    <></>
                  )}
                </React.Fragment>
              ))}
            </Menu.SubMenu>
          );
        })}
      </Menu>
    );
  }, [onAddModule, stores, showMenu, openKeys, isNewAddModuleMenuOn]);

  const onVisibleChange = (visible: boolean) => {
    if (isContentMenuEnabled) {
      history.push({
        pathname: "/admin/modules/new",
        search: groupId ? `?groupId=${groupId}` : "",
      });
    } else {
      setShowMenu(visible);
      if (visible) {
        const pageId = localizationSelected?.id || DEFAULT_UUID;
        const pageName = localizationSelected?.name || "Default";

        useAnalyticsSDK
          ? openModuleCreationMenu({ pageId, pageName })
          : sendSegmentEvent(SEGMENT_EVENTS.OPEN_MODULE_CREATION_MENU, {
              "Page ID": pageId,
              "Page Name": pageName,
            });
      }
    }
  };

  const onSubmitDomainCallback = useCallback(() => {
    setVisibleShopifyModal(true);
    setStep(MODAL_STEPS.LOGIN_SUCCESS);
  }, []);

  const onCreateAccountCallback = useCallback(() => {
    setStep(MODAL_STEPS.CREATE_ACCOUNT);
  }, []);

  const connectToStore = useCallback(() => {
    setStep(MODAL_STEPS.LOGIN);
  }, []);

  const onSubmitRyeDomainCallback = useCallback(() => {
    const count = (stores?.length ?? 0) + 1;
    const from = "Modules page";
    const success = true;

    useAnalyticsSDK
      ? shopifyConnectionFlowCompleted({
          from,
          stores: count,
          success,
        })
      : sendSegmentEvent(SEGMENT_EVENTS.SHOPIFY_CONNECTION_FLOW_COMPLETED, {
          "Number of connected stores": count,
          "Added from": from,
          "Is successful": success,
        });

    setVisibleRyeShopifyModal(true);
    setRyeStep(RYE_MODAL_STEPS.LOGIN_SUCCESS);
  }, [stores?.length]);

  const connectToRyeStore = useCallback(() => {
    setRyeStep(RYE_MODAL_STEPS.LOGIN);
  }, []);

  const modalType = useMemo(() => {
    // this is a temporary port - this logic will be removed once `Content Menu` has been released
    if (visibleBandsintown) {
      return ModuleType.BANDSINTOWN;
    }
    if (visibleSeated) {
      return ModuleType.SEATED;
    }
    if (visibleShopMyShelf) {
      return ModuleType.SHOP_MY_SHELF;
    }
    if (visibleShopList) {
      return ModuleType.SHOP_LIST;
    }
    if (dataCaptureModalVisible) {
      return dataCaptureCreationType;
    }
    if (visibleThroneLink) {
      return ModuleType.THRONE_LINK;
    }
    if (visibleShopifyModal || showShopifyInputModal) {
      return ModuleType.SHOPIFY;
    }
    if (visibleRyeShopifyModal || showRyeShopifyInputModal) {
      return ModuleType.RYE_SHOPIFY;
    }

    return undefined;
  }, [
    visibleBandsintown,
    visibleSeated,
    visibleShopMyShelf,
    visibleShopList,
    dataCaptureModalVisible,
    dataCaptureCreationType,
    visibleThroneLink,
    visibleShopifyModal,
    showShopifyInputModal,
    visibleRyeShopifyModal,
    showRyeShopifyInputModal,
  ]);

  return (
    <React.Fragment>
      {isNewAddModuleMenuOn && (
        <div
          className="ant-modal-mask"
          style={{
            opacity: showMenu ? 1 : 0,
            zIndex: showMenu ? 101 : -1,
            backgroundColor: "rgba(33, 33, 33, 0.80)",
          }}
        />
      )}
      <div
        data-tour="onboarding-add-module"
        className="add-module-card"
        style={isNewAddModuleMenuOn && isSolid ? { zIndex: 9 } : {}}
      >
        <Dropdown
          visible={showMenu}
          placement="topLeft"
          onVisibleChange={onVisibleChange}
          overlay={menu}
          overlayClassName={classNames("add-module__dropdown", {
            "add-module__dropdown__fixed":
              (isNewAddModuleMenuOn && !isSolid) || (height && height <= 700),
          })}
          trigger={["click"]}
        >
          {isSolid ? (
            <Row
              className={classNames("add-module-card__btn", {
                "add-module-card__btn--content-menu": isContentMenuEnabled,
              })}
              align="middle"
              justify="center"
            >
              <TalentIcon name="add-white" />
              <Text
                preset="semibold18"
                className={classNames("m__l--8", "text--white")}
              >
                {buttonText}
              </Text>
            </Row>
          ) : (
            <Row gutter={4} justify="center" align="middle">
              <Col className="height--32">
                <TalentIcon name="add-blue" />
              </Col>
              <Col>
                <Text preset="semibold18" className="text--blue">
                  {buttonText}
                </Text>
              </Col>
            </Row>
          )}
        </Dropdown>
      </div>

      <IfFeatureEnabled feature={FLAGS.FEAT_SB_389_ADD_ITEM_MENU}>
        <ModuleCreationModals
          visible={modalType !== undefined}
          onChangeVisible={() => {
            // this is a temporary port - this logic will be removed once `Content Menu` has been released
            setVisibleBandsintown(false);
            setVisibleSeated(false);
            setVisibleShopMyShelf(false);
            setVisibleShopList(false);
            setVisibleThroneLink(false);
            setVisibleTipsLink(false);
            setDataCaptureModalVisible(false);
            setVisibleShopifyModal(false);
            setShowShopifyInputModal(false);
            setVisibleRyeShopifyModal(false);
            setShowRyeShopifyInputModal(false);
          }}
          type={modalType}
        />
      </IfFeatureEnabled>

      <IfFeatureDisabled feature={FLAGS.FEAT_SB_389_ADD_ITEM_MENU}>
        <ShopifyModal
          toggleModal={setVisibleShopifyModal}
          step={step}
          show={visibleShopifyModal}
          loginCallback={handleLoginCallback}
          loginSuccessCallback={callbackAddShopifyModule}
          goBackToProfileCallback={callbackAddShopifyModule}
          createAccountCallback={onCreateAccountCallback}
          connectToStore={connectToStore}
        />
        <RyeShopifyModal
          toggleModal={setVisibleRyeShopifyModal}
          step={ryeStep}
          show={visibleRyeShopifyModal}
          loginCallback={handleRyeLoginCallback}
          loginSuccessCallback={callbackAddRyeShopifyModule}
          goBackToProfileCallback={callbackAddRyeShopifyModule}
          connectToStore={connectToRyeStore}
        />
        {showShopifyInputModal && (
          <ShopifyStoreDomainInputModal
            toggleModal={setShowShopifyInputModal}
            callback={onSubmitDomainCallback}
          />
        )}
        {showRyeShopifyInputModal && (
          <RyeShopifyStoreDomainInputModal
            toggleModal={setShowRyeShopifyInputModal}
            callback={onSubmitRyeDomainCallback}
            caller="Modules page"
          />
        )}
        <BandsintownEditorModal
          isEdit={false}
          item={undefined}
          visible={visibleBandsintown}
          onChangeVisible={setVisibleBandsintown}
          onConfirmCallback={handleAddBandsintown}
        />
        <SeatedEditorModal
          isEdit={false}
          item={undefined}
          visible={visibleSeated}
          onChangeVisible={setVisibleSeated}
          onConfirmCallback={handleAddSeated}
        />
        <ShopMyShelfEditorModal
          isEdit={false}
          item={undefined}
          visible={visibleShopMyShelf}
          onChangeVisible={setVisibleShopMyShelf}
          onConfirmCallback={handleShopMyShelf}
        />
        <ShopListEditorModal
          isEdit={false}
          item={undefined}
          visible={visibleShopList}
          onChangeVisible={setVisibleShopList}
          onConfirmCallback={handleShopList}
        />
        {isAudiencesAndCampaignsOn && dataCaptureCreationType && (
          <DataCaptureAudienceModal
            type={dataCaptureCreationType}
            visible={dataCaptureModalVisible}
            onChangeVisible={setDataCaptureModalVisible}
            onConfirmCallback={handleDataCaptureFormCreated}
          />
        )}
        {isThroneOn && (
          <ThroneLinkModal
            visible={visibleThroneLink}
            onChangeVisible={setVisibleThroneLink}
            onConfirmCallback={handleThroneLink}
          />
        )}
        {isTipsModuleOn && (
          <TipsLinkModal
            visible={visibleTipsLink}
            onChangeVisible={setVisibleTipsLink}
            onConfirmCallback={handleTipsLink}
          />
        )}
      </IfFeatureDisabled>
    </React.Fragment>
  );
};

export default AddModule;
