import { useCallback, useEffect, useState } from "react";
import { FLAGS, useFeatureIsOn } from "@komi-app/flags-sdk";
import { useTypedSelector } from "../redux/rootReducer";
import { selectShopifyStores } from "../redux/Shopify/selector";
import { MODAL_STEPS } from "../redux/Shopify/types";
import { ModuleType } from "@komi-app/shared-types" 

export function useShopifyModal(
  visible: boolean,
  type: ModuleType | undefined,
  addNewModule: (type: ModuleType) => void,
) {
  const stores = useTypedSelector(selectShopifyStores);

  const [step, setStep] = useState<MODAL_STEPS>(MODAL_STEPS.LOGIN);
  const [showShopifyInputModal, setShowShopifyInputModal] = useState(false);
  const [visibleShopifyModal, setVisibleShopifyModal] = useState(false);
  const isShopifyFixEnabled = useFeatureIsOn(
    FLAGS.FIX_GB_518_SHOPIFY_NEW_CONTENT_MENU,
  );

  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 handleLoginCallback = () => {
    setVisibleShopifyModal(false);
    setShowShopifyInputModal(true);
  };

  useEffect(() => {
    if (!visible || !type) {
      return;
    }
    if (type === ModuleType.SHOPIFY) {
      if (!stores.length) {
        // set login step for new connection
        step !== MODAL_STEPS.LOGIN && setStep(MODAL_STEPS.LOGIN);
        setVisibleShopifyModal(true);
        return;
      } else {
        if (isShopifyFixEnabled) {
          addNewModule(type);
        }
      }
    }
  }, [visible, type, stores]);
  return {
    step,
    showShopifyInputModal,
    setShowShopifyInputModal,
    visibleShopifyModal,
    setVisibleShopifyModal,
    onSubmitDomainCallback,
    onCreateAccountCallback,
    connectToStore,
    handleLoginCallback,
  };
}
