import { TipsLinkItem } from "../../../models/talent/talent-profile-module.model";
import { useDispatch } from "react-redux";
import { useModules } from "../../../hooks/useModules";
import { useAnalytics } from "../../../hooks/useAnalytics";
import { useRyeShopifyModal } from "../../../hooks/useRyeShopifyModal";
import { useShopifyModal } from "../../../hooks/useShopifyModal";
import React, { useCallback } from "react";
import { FLAGS, useFeatureIsOn } from "@komi-app/flags-sdk";
import When from "@komi-app/when";

import { useTypedSelector } from "../../../redux/rootReducer";
import { selectLocalizationSelected } from "../../../redux/User/selector";
import { SEGMENT_EVENTS } from "../../../constants/segment";
import { DCAFormStepsProps } from "../../../components/DataCaptureAudience/CreationModalForms/schemas";
import { dcaFormValuesToItem } from "../../../components/DataCaptureAudience/dca-item-mapping-fns";
import { triggerCheckCollectionAction } from "../../../redux/Shopify/actions";
import { triggerRyeCheckCollectionAction } from "../../../redux/RyeShopify/actions";
import ShopifyModal from "../../../components/ShopifyModal";
import ShopifyStoreDomainInputModal from "../../../components/ShopifyStoreDomainInputModal";
import RyeShopifyModal from "../../../components/RyeShopifyModal";
import RyeShopifyStoreDomainInputModal from "../../../components/RyeShopifyStoreDomainInputModal";
import BandsintownEditorModal from "../../../components/BandsintownEditorModal";
import SeatedEditorModal from "../../../components/SeatedEditorModal";
import ShopMyShelfEditorModal from "../../../components/ShopMyShelfEditorModal";
import ShopListEditorModal from "../../../components/ShopListEditorModal";
import DataCaptureAudienceModal from "../../../components/DataCaptureAudience/DataCaptureCreationModal";
import ThroneLinkModal from "../../../components/ThroneLinkModal";
import DataCaptureModal from "components/DataCaptureModal";
import { useAddNewModule } from "hooks/useAddNewModule";
import TipsLinkModal from "../../../components/TipsLinkModal";
import { contactFormItem } from "services/module-templates/templates/ContactForm";
import { ModuleType } from "@komi-app/shared-types";
import { AffiliateModal } from "../../../components/AffiliateModal";
import { AffiliateProduct } from "@komi-app/affiliate-sdk";
import { AddAffiliateProductResult } from "@komi-app/creator-ui";
import { useCreatorTracking, CreatorEvent } from "@komi-app/analytics-sdk";
import { trackingProps } from "utils/tracking";

interface ModuleCreationModalsProps {
  visible: boolean;
  onChangeVisible: (value: boolean) => void;
  onModuleAdded?: () => void;
  type?: ModuleType;
  groupId?: string;
}

interface ModuleCreationModalsHook {
  hasModal: (type: ModuleType) => boolean;
  openModal: (type: ModuleType) => boolean;
  onChangeModalVisibility: (visibility: boolean) => void;
  isModalOpen: boolean;
  modalType?: ModuleType;
}

export function useModuleCreationModals(): ModuleCreationModalsHook {
  const [isModalOpen, setIsModalOpen] = React.useState(false);
  const [modalType, setModalType] = React.useState<ModuleType | undefined>();

  const hasModal = useCallback((type: ModuleType) => {
    return [
      ModuleType.SHOPIFY,
      ModuleType.RYE_SHOPIFY,
      ModuleType.BANDSINTOWN,
      ModuleType.SEATED,
      ModuleType.SHOP_MY_SHELF,
      ModuleType.SHOP_LIST,
      ModuleType.DATA_CAPTURE_COUPON_CODE,
      ModuleType.DATA_CAPTURE_SECRET_LINK,
      ModuleType.DATA_CAPTURE_SIGNUP,
      ModuleType.THRONE_LINK,
      ModuleType.PAYPAL_LINK,
      ModuleType.VENMO_LINK,
      ModuleType.CASHAPP_LINK,
      ModuleType.PATREON_LINK,
      ModuleType.CONTACT_FORM,
      ModuleType.AFFILIATE,
    ].includes(type);
  }, []);

  const openModal = useCallback(
    (type: ModuleType) => {
      if (!hasModal(type)) {
        return false;
      }
      setModalType(type);
      setIsModalOpen(true);
      return true;
    },
    [hasModal]
  );

  const onChangeModalVisibility = useCallback((visibility: boolean) => {
    if (visibility) {
      // skip - will already be open
    } else {
      setModalType(undefined);
      setIsModalOpen(false);
    }
  }, []);

  return {
    hasModal,
    openModal,
    onChangeModalVisibility,
    isModalOpen,
    modalType,
  };
}

export function ModuleCreationModals({
  visible,
  onChangeVisible,
  onModuleAdded,
  type,
  groupId,
}: ModuleCreationModalsProps) {
  const dispatch = useDispatch();
  const { modules } = useModules();
  const { sendSegmentEvent } = useAnalytics();
  const addNewModule = useAddNewModule(groupId);
  const isShopifyFixEnabled = useFeatureIsOn(
    FLAGS.FIX_GB_518_SHOPIFY_NEW_CONTENT_MENU
  );
  const useAnalyticsSDK = useFeatureIsOn(FLAGS.USE_ANALYTICS_SDK_TALENT);
  const { createTracker } = useCreatorTracking();
  const moduleCreated = createTracker(CreatorEvent.MODULE_CREATED);
  const elementCreated = createTracker(CreatorEvent.ELEMENT_CREATED);

  const {
    ryeStep,
    visibleRyeShopifyModal,
    setVisibleRyeShopifyModal,
    showRyeShopifyInputModal,
    setShowRyeShopifyInputModal,
    onSubmitRyeDomainCallback,
    connectToRyeStore,
    handleRyeLoginCallback,
  } = useRyeShopifyModal(visible, type, (type) => {
    addNewModule(type);
    onModuleAdded();
  });

  function toggleRyeShopifyModal(visibility: boolean) {
    if (!visibility) {
      onChangeVisible(false);
    }
    setVisibleRyeShopifyModal(visibility);
  }

  function toggleRyeShopifyInputModal(visibility: boolean) {
    if (!visibility) {
      onChangeVisible(false);
    }
    setShowRyeShopifyInputModal(visibility);
  }

  const {
    step,
    showShopifyInputModal,
    setShowShopifyInputModal,
    visibleShopifyModal,
    setVisibleShopifyModal,
    onSubmitDomainCallback,
    onCreateAccountCallback,
    connectToStore,
    handleLoginCallback,
  } = useShopifyModal(visible, type, (type) => {
    addNewModule(type);
    onModuleAdded();
  });

  function toggleShopifyModal(visibility: boolean) {
    if (!visibility) {
      onChangeVisible(false);
    }
    setVisibleShopifyModal(visibility);
  }

  function toggleShopifyInputModal(visibility: boolean) {
    if (!visibility) {
      onChangeVisible(false);
    }
    setShowShopifyInputModal(visibility);
  }

  const localizationSelected = useTypedSelector(selectLocalizationSelected);

  const handleAddBandsintown = useCallback(
    (values) => {
      onChangeVisible(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": ModuleType.BANDSINTOWN,
          "Page ID": localizationSelected?.id || null,
          "Page Name": localizationSelected?.name || "Default",
        });
        sendSegmentEvent(SEGMENT_EVENTS.ELEMENT_CREATED, {
          "Module Type": "BANDSINTOWN EVENT",
          "Page ID": localizationSelected?.id || null,
          "Page Name": localizationSelected?.name || "Default",
        });
      }

      addNewModule(ModuleType.BANDSINTOWN, {
        items: [{ ...values, order: 0 }],
      });
      onModuleAdded();
    },
    [localizationSelected, addNewModule, sendSegmentEvent]
  );
  const handleAddSeated = useCallback(
    (values) => {
      onChangeVisible(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": ModuleType.SEATED,
          "Page ID": localizationSelected?.id || null,
          "Page Name": localizationSelected?.name || "Default",
        });
        sendSegmentEvent(SEGMENT_EVENTS.ELEMENT_CREATED, {
          "Module Type": "SEATED EVENT",
          "Page ID": localizationSelected?.id || null,
          "Page Name": localizationSelected?.name || "Default",
        });
      }

      addNewModule(ModuleType.SEATED, {
        items: [{ ...values, order: 0 }],
      });
      onModuleAdded();
    },
    [localizationSelected, addNewModule, sendSegmentEvent]
  );
  const handleShopMyShelf = useCallback(
    (values) => {
      onChangeVisible(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": "SHOPMYSHELF",
          "Page ID": localizationSelected?.id || null,
          "Page Name": localizationSelected?.name || "Default",
        });
        sendSegmentEvent(SEGMENT_EVENTS.ELEMENT_CREATED, {
          "Module Type": "SHOPMYSHELF",
          "Page ID": localizationSelected?.id || null,
          "Page Name": localizationSelected?.name || "Default",
        });
      }
      addNewModule(ModuleType.SHOP_MY_SHELF, {
        name: values.name || "New Module",
        items: [{ url: values.url, order: 0 }],
      });
      onModuleAdded();
    },
    [localizationSelected, addNewModule, sendSegmentEvent]
  );
  const handleShopList = useCallback(
    (values) => {
      onChangeVisible(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": "SHOPLIST",
          "Page ID": localizationSelected?.id || null,
          "Page Name": localizationSelected?.name || "Default",
        });
        sendSegmentEvent(SEGMENT_EVENTS.ELEMENT_CREATED, {
          "Module Type": "SHOPLIST",
          "Page ID": localizationSelected?.id || null,
          "Page Name": localizationSelected?.name || "Default",
        });
      }
      addNewModule(ModuleType.SHOP_LIST, {
        name: values.name || "New Module",
        items: [{ url: values.url, order: 0 }],
      });
      onModuleAdded();
    },
    [localizationSelected, addNewModule, sendSegmentEvent]
  );
  const handleDataCaptureFormCreated = useCallback(
    (values: DCAFormStepsProps) => {
      onChangeVisible(false);

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

      const newModule = dcaFormValuesToItem(values, {
        name: "New Module",
        order: 0,
      });
      addNewModule(newModule.type, {
        name: newModule.name,
        items: [newModule],
      });
      onModuleAdded();
    },
    [localizationSelected, addNewModule, 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": ModuleType.THRONE_LINK,
          "Page ID": localizationSelected?.id || null,
          "Page Name": localizationSelected?.name || "Default",
        });
        sendSegmentEvent(SEGMENT_EVENTS.ELEMENT_CREATED, {
          "Module Type": "THRONE LINK",
          "Page ID": localizationSelected?.id || null,
          "Page Name": localizationSelected?.name || "Default",
        });
      }
      onChangeVisible(false);
      addNewModule(ModuleType.LINK, {
        name: "Throne",
        items: [
          {
            url,
            title: "My Throne Wishlist",
            thumbnail:
              "https://komi-production-assets.s3-accelerate.amazonaws.com/photos/-W1BJQRavoGWC8VlU_qTU.png",
          },
        ],
      });
      onModuleAdded();
    },
    [addNewModule, sendSegmentEvent]
  );

  const handleContactForm = useCallback(
    (values) => {
      const { pageId, pageName, type } = trackingProps(
        ModuleType.CONTACT_FORM,
        localizationSelected
      );

      if (useAnalyticsSDK) {
        moduleCreated({ pageId, pageName, type });
        elementCreated({ pageId, pageName, type });
      } else {
        sendSegmentEvent(SEGMENT_EVENTS.MODULDE_CREATED, {
          "Module Type": ModuleType.CONTACT_FORM,
          "Page ID": localizationSelected?.id || null,
          "Page Name": localizationSelected?.name || "Default",
        });
        sendSegmentEvent(SEGMENT_EVENTS.ELEMENT_CREATED, {
          "Module Type": "CONTACT FORM",
          "Page ID": localizationSelected?.id || null,
          "Page Name": localizationSelected?.name || "Default",
        });
      }
      onChangeVisible(false);
      addNewModule(ModuleType.FORM_DATA, {
        name: "Contact Form",
        items: [values],
      });
      onModuleAdded();
    },
    [addNewModule, 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": localizationSelected?.id || null,
          "Page Name": localizationSelected?.name || "Default",
        });
        sendSegmentEvent(SEGMENT_EVENTS.ELEMENT_CREATED, {
          "Module Type": `${platform} LINK`,
          "Page ID": localizationSelected?.id || null,
          "Page Name": localizationSelected?.name || "Default",
        });
      }
      onChangeVisible(false);
      addNewModule(ModuleType.LINK, {
        name: "Tips",
        items: [
          {
            url,
            title,
            thumbnail: src,
          },
        ],
      });
      onModuleAdded();
    },
    [addNewModule, sendSegmentEvent]
  );
  const handleAffiliateProduct = useCallback(
    async (
      affiliateProduct: AffiliateProduct,
      result: AddAffiliateProductResult
    ) => {
      onChangeVisible(false);

      addNewModule(ModuleType.AFFILIATE, {
        name: "Affiliate Products",
        items: [
          {
            ...affiliateProduct,
            title: result.title,
            visible: true,
          },
        ],
      });
      onModuleAdded();
    },
    [addNewModule]
  );
  const callbackAddShopifyModule = useCallback(() => {
    addNewModule(ModuleType.SHOPIFY);
    dispatch(triggerCheckCollectionAction(true));
    onChangeVisible(false);
    onModuleAdded();
  }, [dispatch, modules, addNewModule, onChangeVisible]);
  const callbackAddRyeShopifyModule = useCallback(() => {
    addNewModule(ModuleType.RYE_SHOPIFY);
    dispatch(triggerRyeCheckCollectionAction(true));
    onChangeVisible(false);
    onModuleAdded();
  }, [dispatch, modules, addNewModule, onChangeVisible]);

  if (!visible || !type) {
    return null;
  }

  return (
    <>
      <When
        value={type}
        then={{
          [ModuleType.SHOPIFY]: (
            <>
              <ShopifyModal
                toggleModal={
                  isShopifyFixEnabled
                    ? toggleShopifyModal
                    : setVisibleShopifyModal
                }
                step={step}
                show={visibleShopifyModal}
                loginCallback={handleLoginCallback}
                loginSuccessCallback={callbackAddShopifyModule}
                goBackToProfileCallback={callbackAddShopifyModule}
                createAccountCallback={onCreateAccountCallback}
                connectToStore={connectToStore}
              />
              {showShopifyInputModal && (
                <ShopifyStoreDomainInputModal
                  toggleModal={
                    isShopifyFixEnabled
                      ? toggleShopifyInputModal
                      : setShowShopifyInputModal
                  }
                  callback={onSubmitDomainCallback}
                />
              )}
            </>
          ),
          [ModuleType.RYE_SHOPIFY]: (
            <>
              <RyeShopifyModal
                toggleModal={
                  isShopifyFixEnabled
                    ? toggleRyeShopifyModal
                    : setVisibleRyeShopifyModal
                }
                step={ryeStep}
                show={visibleRyeShopifyModal}
                loginCallback={handleRyeLoginCallback}
                loginSuccessCallback={callbackAddRyeShopifyModule}
                goBackToProfileCallback={callbackAddRyeShopifyModule}
                connectToStore={connectToRyeStore}
              />
              {showRyeShopifyInputModal && (
                <RyeShopifyStoreDomainInputModal
                  toggleModal={
                    isShopifyFixEnabled
                      ? toggleRyeShopifyInputModal
                      : setShowRyeShopifyInputModal
                  }
                  callback={onSubmitRyeDomainCallback}
                  caller="Modules page"
                />
              )}
            </>
          ),
          [ModuleType.BANDSINTOWN]: (
            <BandsintownEditorModal
              isEdit={false}
              item={undefined}
              visible
              onChangeVisible={onChangeVisible}
              onConfirmCallback={handleAddBandsintown}
            />
          ),
          [ModuleType.SEATED]: (
            <SeatedEditorModal
              isEdit={false}
              item={undefined}
              visible
              onChangeVisible={onChangeVisible}
              onConfirmCallback={handleAddSeated}
            />
          ),
          [ModuleType.SHOP_MY_SHELF]: (
            <ShopMyShelfEditorModal
              isEdit={false}
              item={undefined}
              visible
              onChangeVisible={onChangeVisible}
              onConfirmCallback={handleShopMyShelf}
            />
          ),
          [ModuleType.SHOP_LIST]: (
            <ShopListEditorModal
              isEdit={false}
              item={undefined}
              visible
              onChangeVisible={onChangeVisible}
              onConfirmCallback={handleShopList}
            />
          ),
          [ModuleType.DATA_CAPTURE_COUPON_CODE]: (
            <DataCaptureAudienceModal
              type={type}
              visible
              onChangeVisible={onChangeVisible}
              onConfirmCallback={handleDataCaptureFormCreated}
            />
          ),
          [ModuleType.DATA_CAPTURE_SECRET_LINK]: (
            <DataCaptureAudienceModal
              type={type}
              visible
              onChangeVisible={onChangeVisible}
              onConfirmCallback={handleDataCaptureFormCreated}
            />
          ),
          [ModuleType.DATA_CAPTURE_SIGNUP]: (
            <DataCaptureAudienceModal
              type={type}
              visible
              onChangeVisible={onChangeVisible}
              onConfirmCallback={handleDataCaptureFormCreated}
            />
          ),
          [ModuleType.THRONE_LINK]: (
            <ThroneLinkModal
              visible
              onChangeVisible={onChangeVisible}
              onConfirmCallback={handleThroneLink}
            />
          ),
          [ModuleType.PAYPAL_LINK]: (
            <TipsLinkModal
              visible
              platform={ModuleType.PAYPAL_LINK}
              onChangeVisible={onChangeVisible}
              onConfirmCallback={handleTipsLink}
            />
          ),
          [ModuleType.VENMO_LINK]: (
            <TipsLinkModal
              visible
              platform={ModuleType.VENMO_LINK}
              onChangeVisible={onChangeVisible}
              onConfirmCallback={handleTipsLink}
            />
          ),
          [ModuleType.CASHAPP_LINK]: (
            <TipsLinkModal
              visible
              platform={ModuleType.CASHAPP_LINK}
              onChangeVisible={onChangeVisible}
              onConfirmCallback={handleTipsLink}
            />
          ),
          [ModuleType.PATREON_LINK]: (
            <TipsLinkModal
              visible
              platform={ModuleType.PATREON_LINK}
              onChangeVisible={onChangeVisible}
              onConfirmCallback={handleTipsLink}
            />
          ),
          [ModuleType.CONTACT_FORM]: (
            <DataCaptureModal
              show
              toggleModal={onChangeVisible}
              onFinish={handleContactForm}
              item={contactFormItem}
              isContactForm
              isNew
            />
          ),
          [ModuleType.AFFILIATE]: (
            <AffiliateModal
              visible
              onChangeVisible={onChangeVisible}
              onConfirmCallback={handleAffiliateProduct}
            />
          ),
        }}
      />
    </>
  );
}
