import { Alert, Button, Spin, Tooltip, Row, Col } from "antd";
import { useTypedSelector } from "redux/rootReducer";
import { RYE_SHOPIFY_MODULE_TYPE } from "constants/shopify";
import DragDropContext from "components/DragDropContext";
import { Icon } from "components/Icon";
import PortalComponent from "components/PortalComponent/PortalComponent";
import ShopifyProductCard from "components/ShopifyProductCard";
import ShopifyStoreSelection from "components/ShopifyStoreSelection";
import { Text } from "components/Typography";
import { ReactComponent as InfoIcon } from "icons/info.svg";
import {
  ShopifyProductItem,
  TalentModuleMixItem,
  TalentProfileModule,
} from "models/talent/talent-profile-module.model";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { DraggableProvidedDragHandleProps } from "react-beautiful-dnd";
import { isMobile } from "react-device-detect";
import { selectRyeTriggerCheckCollection } from "redux/RyeShopify/selector";
import {
  selectLocalizationSelected,
  selectTalentProfile,
  selectTalentProfileModulesOrigin,
} from "redux/User/selector";
import { ryeShopifyService } from "services";
import EmptyModule from "./EmptyModule";

import classNames from "classnames";
import ConfirmDeleteModal from "components/ShopifyProductCard/ProductDeleteModalConfirm";
import { SEGMENT_EVENTS } from "constants/segment";
import { useAnalytics } from "hooks/useAnalytics";
import { useModules } from "hooks/useModules";
import { ArrayServices } from "utils/array";
import notification from "utils/notification";
import ModuleEditor from "../ModuleEditor";
import "./ModuleShopify.scss";
import { triggerCheckCollectionAction } from "redux/Shopify/actions";
import { useDispatch } from "react-redux";
import { isEmptyModule } from "utils/modules";
import { selectRyeShopifyStores } from "redux/RyeShopify/selector";
import { RYE_MODAL_STEPS, RyeShopifyStore } from "redux/RyeShopify/types";
import RyeShopifyModal from "components/RyeShopifyModal";
import RyeShopifyStoreDomainInputModal from "components/RyeShopifyStoreDomainInputModal";
import { NormalizedCollection, PageInfo } from "services/ryeShopifyServices";

import { ModuleType } from "@komi-app/shared-types"
import { FLAGS, useFeatureIsOn } from "@komi-app/flags-sdk";
import { useCreatorTracking, CreatorEvent } from "@komi-app/analytics-sdk";
import { trackingProps } from "utils/tracking";

const PRODUCT_TYPES = {
  COLLECTION: 1,
  INDIVIDUAL: 2,
};

const ShopifyProductCardMemo = React.memo(ShopifyProductCard);

interface ModuleShopifyProps {
  module: TalentProfileModule<ShopifyProductItem>;
  dragHandleProps?: DraggableProvidedDragHandleProps;
  active?: boolean;
}

const RyeModuleShopify: React.FC<ModuleShopifyProps> = ({
  module,
  dragHandleProps,
  active,
}) => {
  const dispatch = useDispatch();
  const { sendSegmentEvent } = useAnalytics();
  const profileContext = useModules();
  const [items, setItems] = useState<ShopifyProductItem[]>([]);
  const [storeSelected, setStoreSelected] = useState<RyeShopifyStore>();
  const [collectionPages, setCollectionPages] = useState<
    { collections: NormalizedCollection[]; pageInfo: PageInfo }[]
  >([]);
  const collectionList = collectionPages.flatMap((x) => x.collections);
  const [isAdding, setIsAdding] = useState<boolean>(false);
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [isShowAlert, setIsShowAlert] = useState(false);
  const [productPages, setProductPages] = useState<any[][]>([]);
  const [hasProducts, setHasProducts] = useState<boolean>();
  const productList = productPages.flat();
  const [hasCollections, setHasCollections] = useState<boolean>();
  const [collectionSelected, setCollectionSelected] = useState<string>();
  const [productsSelected, setProductsSelected] = useState<
    Array<ShopifyProductItem>
  >([]);

  const productsAdded: Array<ShopifyProductItem> = productList.filter(
    (item: any) => module.items[0]?.itemIds?.some((id) => id === item.id)
  );
  const availableProducts: Array<ShopifyProductItem> = productList.filter(
    (item: ShopifyProductItem) =>
      !productsAdded?.some((product: any) => product.id === item.id)
  );

  const [productType, setProductType] = useState<number>();
  const [collectionName, setCollectionName] = useState<string>();
  const [showShopifyInputModal, setShowShopifyInputModal] = useState(false);
  const [visibleConfirmDeleteModal, setVisibleConfirmDeleteModal] =
    useState(false);
  const [visibleModal, setVisibleModal] = useState<boolean>(false);
  const [step, setStep] = useState<RYE_MODAL_STEPS>(RYE_MODAL_STEPS.LOADING);
  const [isFetching, setIsFetching] = useState(false);
  const stores = useTypedSelector(selectRyeShopifyStores);
  const talentProfile = useTypedSelector(selectTalentProfile);
  const trigger = useTypedSelector(selectRyeTriggerCheckCollection);
  const talentModulesRevert = useTypedSelector(
    selectTalentProfileModulesOrigin
  );
  const localizationSelected = useTypedSelector(selectLocalizationSelected);
  const useAnalyticsSDK = useFeatureIsOn(FLAGS.USE_ANALYTICS_SDK_TALENT);
  const { createTracker } = useCreatorTracking()
  const elementCreate = createTracker(CreatorEvent.ELEMENT_CREATED);
  const viewShopifyConnectionFlow = createTracker(CreatorEvent.VIEW_SHOPIFY_CONNECTION_FLOW);
  const shopifyConnectionFlowCompleted = createTracker(CreatorEvent.SHOPIFY_CONNECTION_FLOW_COMPLETED);

  const actualStores = useMemo(
    () => stores.filter((store) => store.connected),
    [stores]
  );

  const handleCheckRyeCollection = async (store?: RyeShopifyStore) => {
    if (!store) return;

    try {
      const [collectionsResponse, productsResponse] = await Promise.all([
        ryeShopifyService().fetchCollections(store.domain),
        ryeShopifyService().fetchProducts(store.domain),
      ]);

      setHasCollections(!!collectionsResponse.collections.length);
      setHasProducts(!!productsResponse.length);

      if (!collectionsResponse.collections.length) {
        if (!productsResponse.length) {
          onOpenModal(RYE_MODAL_STEPS.EMPTY);
        } else {
          setProductPages([productsResponse]);
          setProductType(PRODUCT_TYPES.INDIVIDUAL);
          onOpenModal(RYE_MODAL_STEPS.ADD_PRODUCT);
        }
      } else {
        onOpenModal(RYE_MODAL_STEPS.SELECT_MODULE_TYPE);
      }
    } catch (e) {
      console.error("[module:rye-shopify:check-collection]", e);

      notification.error({
        message: "Something went wrong with Shopify service",
      });
    }

    setIsFetching(false);
  };

  useEffect(() => {
    if (!storeSelected && actualStores.length) {
      setStoreSelected(actualStores[0]);
    }

    /**
     * When a store is added for the first time
     */
    if (
      trigger &&
      module.type === ModuleType.RYE_SHOPIFY &&
      actualStores.length === 1
    ) {
      setIsFetching(true);
      dispatch(triggerCheckCollectionAction(false));

      handleCheckRyeCollection(actualStores[0]);
    }
  }, [trigger, module.type, actualStores, hasCollections, hasProducts]);

  const fetchData = useCallback(
    async (currentModule: any) => {
      try {
        setIsLoading(true);
        const storeDomain = currentModule.items[0]?.shop || "";

        const store = actualStores.length
          ? actualStores.filter((store) => store.domain === storeDomain)[0]
          : talentProfile?.shopifyMerchants[storeDomain];
        setStoreSelected(store);

        if (
          currentModule.type === RYE_SHOPIFY_MODULE_TYPE.RYE_SHOPIFY_COLLECTION
        ) {
          const collectionId = currentModule.items[0].collectionId;
          const collection = await ryeShopifyService().fetchCollection(
            collectionId
          );

          setCollectionName(collection?.title);
          setItems(collection.products);
          return;
        }
        if (
          currentModule.type === RYE_SHOPIFY_MODULE_TYPE.RYE_SHOPIFY_PRODUCT
        ) {
          setProductType(PRODUCT_TYPES.INDIVIDUAL);
          const productIds: string[] = currentModule.items[0].itemIds || [];
          const products = await ryeShopifyService().fetchProductsByIDs(
            store.domain,
            productIds
          );
          setItems(products);
          setProductsSelected(products);
        }
        setIsShowAlert(false);
      } catch (error) {
      } finally {
        setIsLoading(false);
      }
    },
    [actualStores]
  );

  useEffect(() => {
    if (actualStores.length && module.items[0]) {
      fetchData(module);
    }
    return () => {};
  }, [fetchData, actualStores, module]);

  const onDeleteItem = useCallback(
    (item: ShopifyProductItem) => {
      const itemsUpdate = module.items[0].itemIds?.filter(
        (id) => id !== item.id
      );
      setItems((items) => items.filter((el) => el.id !== item.id));
      profileContext.setModule({
        ...module,
        items: [{ ...module.items[0], itemIds: itemsUpdate }],
        isUpdate: true,
      });
    },
    [module, profileContext.setModule]
  );

  const onDropEndProducts = useCallback(
    (list: ShopifyProductItem[]) => {
      const itemsUpdate = list.map((item) => item.id);
      setItems(list);
      profileContext.setModule({
        ...module,
        items: [
          { ...module.items[0], itemIds: itemsUpdate },
        ] as ShopifyProductItem[],
        isUpdate: true,
      });
    },
    [module, profileContext.setModule]
  );

  const onOpenModal = (step: RYE_MODAL_STEPS) => {
    setStep(step);
    setVisibleModal(true);
  };

  const handleSubmit = useCallback(() => {
    setIsFetching(true);
    handleCheckRyeCollection(storeSelected);

    setIsAdding(true);
    setIsShowAlert(true);
    setProductPages([]);
    setCollectionPages([]);
    setProductsSelected([]);
  }, [actualStores, storeSelected]);

  const handleChangeStore = useCallback(
    (store) => {
      setStoreSelected(store);
    },
    [setStoreSelected]
  );

  const handleAddInvidualProduct = useCallback(async () => {
    setIsFetching(true);
    onOpenModal(RYE_MODAL_STEPS.ADD_MORE_PRODUCT);
    if (module.items.length) {
      const store = actualStores.filter(
        (store) => store.domain === module.items[0].shop
      )[0];
      setStoreSelected(store);

      let productsResponse;
      if (module.type === RYE_SHOPIFY_MODULE_TYPE.RYE_SHOPIFY_COLLECTION) {
        productsResponse = await ryeShopifyService().fetchProducts(
          store.domain
        );
      } else if (module.type === RYE_SHOPIFY_MODULE_TYPE.RYE_SHOPIFY_PRODUCT) {
        productsResponse = await ryeShopifyService().fetchProducts(
          store.domain
        );
      }

      if (productsResponse) {
        setProductPages([productsResponse]);
        setProductsSelected([]);
      }

      setIsFetching(false);
    } else {
      setIsFetching(false);
    }
  }, [isAdding, module.items, actualStores]);

  const fetchMoreCollections = async () => {
    if (!storeSelected) {
      return;
    }

    const lastPage = collectionPages[collectionPages.length - 1];
    if (!lastPage.pageInfo.hasNextPage) {
      return;
    }

    const newCollectionsResponse = await ryeShopifyService().fetchCollections(
      storeSelected.domain,
      lastPage.pageInfo.endCursor
    );

    setCollectionPages((current: any) => [...current, newCollectionsResponse]);
  };

  const fetchMoreProducts = async () => {
    if (!storeSelected) {
      return;
    }

    const lastPage = productPages[productPages.length - 1];
    if (lastPage.length < ryeShopifyService().productsPageSize) {
      return;
    }

    const newProductsResponse = await ryeShopifyService().fetchProducts(
      storeSelected.domain,
      undefined,
      productList.length
    );

    setProductPages((current: any) => [...current, newProductsResponse]);
  };

  const handleSelectProductType = async () => {
    setIsFetching(true);
    const storeDetail = actualStores?.filter(
      (store) => store.domain === storeSelected?.domain
    )[0];

    switch (productType) {
      case PRODUCT_TYPES.COLLECTION:
        onOpenModal(RYE_MODAL_STEPS.ADD_COLLECTION);
        const collectionsResponse = await ryeShopifyService().fetchCollections(
          storeDetail.domain
        );

        if (!collectionsResponse.collections.length) {
          const productsResponse = await ryeShopifyService().fetchProducts(
            storeDetail.domain
          );

          setIsFetching(false);

          if (!productsResponse.length) {
            onOpenModal(RYE_MODAL_STEPS.EMPTY);
          } else {
            setProductType(PRODUCT_TYPES.INDIVIDUAL);
            setProductPages([productsResponse]);
            onOpenModal(RYE_MODAL_STEPS.ADD_PRODUCT);
          }
        } else {
          setCollectionPages([collectionsResponse]);

          onOpenModal(RYE_MODAL_STEPS.ADD_COLLECTION);
          setIsFetching(false);
        }
        break;

      default:
        onOpenModal(RYE_MODAL_STEPS.ADD_PRODUCT);

        ryeShopifyService()
          .fetchProducts(storeDetail.domain)
          .then((products: any) => {
            if (!products.length) {
              setIsFetching(false);
              onOpenModal(RYE_MODAL_STEPS.EMPTY);
              return;
            }
            setProductPages([products]);
            setIsFetching(false);
          })
          .catch((e) => console.log(e));
        break;
    }
  };

  const onAddCollectionCallback = useCallback(() => {
    if (!collectionSelected) {
      notification.error({
        message: "Please select the collection!",
      });
      return;
    }
    const colection = collectionList.filter((collection: any) => {
      return collection.id === collectionSelected;
    })[0];

    setCollectionName(colection?.title || "");

    const moduleEdit = {
      ...module,
      items: [
        {
          shop: storeSelected?.domain,
          collectionId: collectionSelected,
        },
      ],
      isUpdate: true,
      type: RYE_SHOPIFY_MODULE_TYPE.RYE_SHOPIFY_COLLECTION,
    };
    profileContext.setModule(moduleEdit);
    setVisibleModal(false);

    const {
        pageId,
        pageName,
        type
      } = trackingProps(moduleEdit.type, localizationSelected)

      useAnalyticsSDK
        ? elementCreate({ pageId, pageName, type })
        : sendSegmentEvent(SEGMENT_EVENTS.ELEMENT_CREATED, {
          "Module Type": moduleEdit.type,
          "Page ID": localizationSelected?.id || null,
          "Page Name": localizationSelected?.name || "Default",
        });
  }, [collectionSelected, module, storeSelected, profileContext.setModule]);

  const onAddProductCallBack = useCallback(() => {
    if (!productsSelected.length) {
      notification.error({
        message: "Please select products!",
      });
      return;
    }

    const moduleEdit = {
      ...module,
      items: [
        {
          ...module.items[0],
          shop: storeSelected?.domain,
          itemIds: [
            ...productsSelected.map((item) => item.id),
            ...(module.items[0]?.itemIds ?? []),
          ],
        } as TalentModuleMixItem,
      ],
      isUpdate: true,
      type: RYE_SHOPIFY_MODULE_TYPE.RYE_SHOPIFY_PRODUCT,
    };

    profileContext.setModule(moduleEdit);
    
    const {
      pageId,
      pageName,
      type
    } = trackingProps(moduleEdit.type, localizationSelected)

    useAnalyticsSDK
      ? elementCreate({ pageId, pageName, type })
      : sendSegmentEvent(SEGMENT_EVENTS.ELEMENT_CREATED, {
        "Module Type": moduleEdit.type,
        "Page ID": localizationSelected?.id || null,
        "Page Name": localizationSelected?.name || "Default",
      });
    setVisibleModal(false);
  }, [
    module,
    productsSelected,
    storeSelected?.domain,
    localizationSelected,
    profileContext.setModule,
    sendSegmentEvent,
  ]);

  const onLoginSuccessCallback = useCallback(() => {
    setIsFetching(true);
    const store = actualStores[actualStores.length - 1]; // the last store added
    setStoreSelected(store);
    handleCheckRyeCollection(store);
  }, [actualStores]);

  const onSelectProduct = useCallback(
    (productSelect: ShopifyProductItem) => {
      const products =
        productsSelected?.filter((product) => product.id === productSelect.id)
          .length > 0
          ? productsSelected.filter(
              (product) => product.id !== productSelect.id
            )
          : ArrayServices.unshift(productsSelected, productSelect);
      setProductsSelected(products);
    },
    [productsSelected, productPages]
  );

  const connectToStore = useCallback(() => {
    const from = "Modules page";
    const count = stores?.length ?? 0

    useAnalyticsSDK
      ? viewShopifyConnectionFlow({ from, stores: count })
      : sendSegmentEvent(SEGMENT_EVENTS.VIEW_SHOPIFY_CONNECTION_FLOW, {
        "Number of connected stores": count,
        "Added from": from,
      });

    return onOpenModal(RYE_MODAL_STEPS.LOGIN);
  }, [stores?.length]);
  const goBackToProductType = useCallback(
    () => onOpenModal(RYE_MODAL_STEPS.SELECT_MODULE_TYPE),
    []
  );

  const onReload = async () => {
    if (!storeSelected) {
      return;
    }

    if (productType === PRODUCT_TYPES.COLLECTION) {
      const collectionsResponse = await ryeShopifyService().fetchCollections(
        storeSelected.domain
      );
      if (!collectionsResponse.collections.length) {
        const productsResponse = await ryeShopifyService().fetchProducts(
          storeSelected.domain
        );
        if (!productsResponse.length) {
          return;
        }
        setProductType(PRODUCT_TYPES.INDIVIDUAL);
        setProductPages([productsResponse]);
        onOpenModal(RYE_MODAL_STEPS.ADD_PRODUCT);
        return;
      }
      setCollectionPages([collectionsResponse]);
      const selected = collectionsResponse.collections.find(
        (item: any) => item.id === collectionSelected
      );
      if (!selected?.products?.length) {
        return;
      }
      setCollectionName(selected?.title || "");

      setItems(selected.products);
      const moduleEdit = {
        ...module,
        items: [
          {
            shop: storeSelected?.domain,
            collectionId: selected.id,
          },
        ],
        isUpdate: true,
        type: RYE_SHOPIFY_MODULE_TYPE.RYE_SHOPIFY_COLLECTION,
      };
      profileContext.setModule(moduleEdit);
      setVisibleModal(false);
      return;
    }
    const productsResponse = await ryeShopifyService().fetchProducts(
      storeSelected.domain
    );
    if (!productsResponse.length) {
      return;
    }
    onOpenModal(RYE_MODAL_STEPS.ADD_PRODUCT);
    setProductPages([productsResponse]);
    setTimeout(() => {
      onOpenModal(RYE_MODAL_STEPS.ADD_PRODUCT);
    }, 150);
  };

  const onDeleteCollection = () => {
    setVisibleConfirmDeleteModal(true);
  };

  const onConfirmDeteleCollection = useCallback(() => {
    setItems([]);
    profileContext.setModule({ ...module, items: [], isUpdate: true });
    setVisibleConfirmDeleteModal(false);
  }, [profileContext.setModule]);

  return (
    <React.Fragment>
      <ModuleEditor
        module={module}
        dragHandleProps={dragHandleProps}
        InfoTooltip={
          module.items.length && !isShowAlert ? (
            <Tooltip
              className="m__l--12 align__self--center"
              overlayClassName="module-shopify__tooltip"
              placement={isMobile ? "bottom" : "bottomLeft"}
              title={
                productType === PRODUCT_TYPES.COLLECTION
                  ? "This module contains a collection. To add another collection or individual products, create a new product module. If you want to reorder items, you can do so from your Shopify account."
                  : "This module contains individual products. To add a collection, create a new product module."
              }
              color={"#FFFFFF"}
            >
              <div className="height--24 width--24">
                <Icon name="info" width={24} height={24} />
              </div>
            </Tooltip>
          ) : undefined
        }
      >
        <Spin spinning={isLoading}>
          {isEmptyModule(module) ||
          module.type === ModuleType.RYE_SHOPIFY ? (
            <>
              <Text preset="regular14">Select your store</Text>
              <ShopifyStoreSelection
                items={actualStores.filter(
                  (store) => store?.connected === true
                )}
                onChange={handleChangeStore}
                value={storeSelected}
                onConnectToAnotherStore={connectToStore}
              />
              <div className="divider m__t--24" />
              <EmptyModule
                caption="Add Products From Your Shopify Store"
                titleAction="Add Products"
                onClick={handleSubmit}
              />
            </>
          ) : (
            <React.Fragment>
              {!!module.items.length && isShowAlert && (
                <Alert
                  message={undefined}
                  className={classNames(
                    "m__b--16 p__x--16 p__y--8 bg--grey shopify-module__alert",
                    productType !== PRODUCT_TYPES.COLLECTION &&
                      "align__items--center"
                  )}
                  description={
                    productType === PRODUCT_TYPES.COLLECTION
                      ? "This module contains a collection. To add another collection or individual products, create a new product module. If you want to reorder items, you can do so from your Shopify account."
                      : "This module contains individual products. To add a collection, create a new product module."
                  }
                  icon={<InfoIcon />}
                  showIcon
                  closeText={
                    <Icon width={24} height={24} name="close-outline" />
                  }
                  onClose={() => setIsShowAlert(false)}
                />
              )}

              {module.type ===
              RYE_SHOPIFY_MODULE_TYPE.RYE_SHOPIFY_COLLECTION ? (
                <>
                  {items.length ? (
                    <Row align="middle" wrap={false} className="m__b--14">
                      <Col>
                        <Text preset="semibold18">Shopify collection</Text>
                      </Col>
                      <Col flex={"1"} className="m__l--20">
                        {storeSelected?.domain && (
                          <Text
                            preset="medium14"
                            className="opacity-6"
                          >{`${storeSelected.domain} - Shopify store`}</Text>
                        )}
                      </Col>
                      <Col className="height--24" onClick={onDeleteCollection}>
                        <Icon name="trash" />
                      </Col>
                    </Row>
                  ) : null}
                  <div className="m__t--16 border--grey2 p--20">
                    <Row align="middle" wrap={false} className="m__b--14">
                      <Col flex={"1"}>
                        <Text preset="semibold18">{collectionName}</Text>
                      </Col>
                      <Col className="height--24">
                        <Text
                          preset="regular16"
                          className="m__b--16 m__t--4 leading-24"
                        >
                          <Text preset="medium14" className="opacity-6">
                            {items.length}&nbsp;
                            {items.length > 1 ? "products" : "product"}
                          </Text>
                        </Text>
                      </Col>
                    </Row>
                    <DragDropContext
                      droppableId="collection-child-drop"
                      listClassName="collection-list"
                      itemIdPrefix="collection"
                      list={items}
                      onDropEndCallback={onDropEndProducts}
                    >
                      {(dragProvided, snapshot, item, itemIndex) => {
                        const isRender = active ? active : itemIndex < 2;
                        return isRender ? (
                          <PortalComponent
                            innerRef={dragProvided.innerRef}
                            key={itemIndex}
                            namespaceClass="collection-list"
                            provided={dragProvided}
                            snapshot={snapshot}
                            single={items?.length === 1}
                          >
                            <ShopifyProductCardMemo
                              disableDragDrop={items?.length <= 1}
                              index={itemIndex}
                              item={item}
                              type={PRODUCT_TYPES.COLLECTION}
                              showPrice
                              onDelete={onDeleteItem}
                              active={active}
                              dragHandleProps={dragProvided.dragHandleProps}
                            />
                          </PortalComponent>
                        ) : itemIndex < 2 ? (
                          <PortalComponent
                            innerRef={dragProvided.innerRef}
                            key={itemIndex}
                            namespaceClass="collection-list"
                            provided={dragProvided}
                            snapshot={snapshot}
                            single={items?.length === 1}
                          >
                            <ShopifyProductCardMemo
                              disableDragDrop={items?.length <= 1}
                              index={itemIndex}
                              item={item}
                              type={PRODUCT_TYPES.COLLECTION}
                              showPrice
                              onDelete={onDeleteItem}
                              active={active}
                              dragHandleProps={dragProvided.dragHandleProps}
                            />
                          </PortalComponent>
                        ) : (
                          <></>
                        );
                      }}
                    </DragDropContext>
                  </div>
                  {!active && items.length > 2 && (
                    <div className="d--flex justify__content--end align__items--center m__t--20 cursor-pointer">
                      <Text preset="medium14" className="opacity-6">
                        +{items.length - 2} More
                      </Text>
                    </div>
                  )}
                </>
              ) : (
                <>
                  <div className="d--flex justify__content--between align__items--center m__b--22">
                    <Button
                      type="link"
                      className="p--0"
                      onClick={handleAddInvidualProduct}
                    >
                      <div className="d--flex justify__content--start align__items--center">
                        <Icon name="add-blue" />
                        <Text
                          preset="semibold18"
                          className="text--blue m__l--4"
                        >
                          Add Products
                        </Text>
                      </div>
                    </Button>
                    <Text preset="medium14" className="opacity-6">
                      {items.length}&nbsp;
                      {items.length > 1 ? "products added" : "product added"}
                    </Text>
                  </div>
                  <DragDropContext
                    droppableId="shopify-child-drop"
                    listClassName="collection-list"
                    itemIdPrefix="shopify"
                    list={items}
                    onDropEndCallback={onDropEndProducts}
                  >
                    {(dragProvided, snapshot, item, itemIndex) => {
                      const isRender = active ? active : itemIndex < 2;
                      return isRender ? (
                        <PortalComponent
                          key={itemIndex}
                          innerRef={dragProvided.innerRef}
                          namespaceClass="collection-list"
                          provided={dragProvided}
                          snapshot={snapshot}
                          single={items?.length === 1}
                        >
                          <ShopifyProductCardMemo
                            disableDragDrop={items?.length <= 1}
                            index={itemIndex}
                            item={item}
                            type={PRODUCT_TYPES.INDIVIDUAL}
                            showPrice
                            onDelete={onDeleteItem}
                            active={active}
                            dragHandleProps={dragProvided.dragHandleProps}
                          />
                        </PortalComponent>
                      ) : (
                        <></>
                      );
                    }}
                  </DragDropContext>
                </>
              )}
              {!active && items.length > 2 && (
                <div className="d--flex justify__content--end align__items--center m__t--20 cursor-pointer">
                  <Text preset="medium14" className="opacity-6">
                    +{items.length - 2} More
                  </Text>
                </div>
              )}
            </React.Fragment>
          )}
        </Spin>
      </ModuleEditor>

      <ConfirmDeleteModal
        show={visibleConfirmDeleteModal}
        toggleModal={setVisibleConfirmDeleteModal}
        cancelLabel="NO THANKS"
        confirmLabel="DELETE"
        title="Are you sure you want to delete this collection?"
        description="The collection will be deleted from your Komi profile and you can’t undo this action."
        handleConfirm={onConfirmDeteleCollection}
      />

      <RyeShopifyModal
        show={visibleModal}
        toggleModal={setVisibleModal}
        reloadCallback={onReload}
        step={step}
        loading={isFetching}
        collections={collectionList}
        onSelectColection={setCollectionSelected}
        onSelectProductType={setProductType}
        productType={productType}
        products={productList}
        hasMoreProducts={
          productPages[productPages.length - 1]?.length ===
          ryeShopifyService().productsPageSize
        }
        fetchMoreProducts={fetchMoreProducts}
        hasProducts={hasProducts}
        hasCollections={hasCollections}
        hasMoreCollections={
          collectionPages[collectionPages.length - 1]?.pageInfo.hasNextPage
        }
        fetchMoreCollections={fetchMoreCollections}
        productsSelected={productsSelected}
        productsAdded={productsAdded}
        availableProducts={availableProducts}
        onSelectProduct={onSelectProduct}
        addCollectionCallback={onAddCollectionCallback}
        addProductCallback={onAddProductCallBack}
        loginSuccessCallback={onLoginSuccessCallback}
        connectToStore={connectToStore}
        loginCallback={() => {
          setVisibleModal(false);
          setShowShopifyInputModal(true);
        }}
        selectModuleTypeCallback={handleSelectProductType}
        goBackToProductTypeCallback={goBackToProductType}
      />

      {showShopifyInputModal && (
        <RyeShopifyStoreDomainInputModal
          toggleModal={setShowShopifyInputModal}
          callback={() => {
            const from = "Modules page"
            const success = true
            const count = (stores?.length ?? 0) + 1

            useAnalyticsSDK
              ? shopifyConnectionFlowCompleted({
                from,
                stores: count,
                success
              })
              : sendSegmentEvent(SEGMENT_EVENTS.SHOPIFY_CONNECTION_FLOW_COMPLETED, {
                  "Number of connected stores": count,
                  "Added from": from,
                  "Is successful": success,
                });
            return onOpenModal(RYE_MODAL_STEPS.LOGIN_SUCCESS);
          }}
          caller="Modules page"
        />
      )}
    </React.Fragment>
  );
};

export default React.memo(RyeModuleShopify);
