import { useCallback, useEffect, useState } from 'react'
import { FLAGS, useFeatureIsOn } from '@komi-app/flags-sdk'
import { RYE_MODAL_STEPS } from '../redux/RyeShopify/types'
import { useTypedSelector } from '../redux/rootReducer'
import { selectRyeShopifyStores } from '../redux/RyeShopify/selector'
import { selectShopifyStores } from '../redux/Shopify/selector'
import { SEGMENT_EVENTS } from '../constants/segment'
import { useAnalytics } from './useAnalytics'
import { ModuleType } from '@komi-app/meta-profiles'
import { useCreatorTracking, CreatorEvent } from '@komi-app/analytics-sdk'

export function useRyeShopifyModal(
  visible: boolean,
  type: ModuleType | undefined,
  addNewModule: (type: ModuleType) => void
) {
  const { sendSegmentEvent } = useAnalytics()
  const ryeStores = useTypedSelector(selectRyeShopifyStores)
  const stores = useTypedSelector(selectShopifyStores)
  const isShopifyFixEnabled = useFeatureIsOn(
    FLAGS.FIX_GB_518_SHOPIFY_NEW_CONTENT_MENU
  )

  const [ryeStep, setRyeStep] = useState<RYE_MODAL_STEPS>(RYE_MODAL_STEPS.LOGIN)
  const [visibleRyeShopifyModal, setVisibleRyeShopifyModal] = useState(false)
  const [showRyeShopifyInputModal, setShowRyeShopifyInputModal] =
    useState(false)

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

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

  const useAnalyticsSDK = useFeatureIsOn(FLAGS.USE_ANALYTICS_SDK_TALENT)
  const { createTracker } = useCreatorTracking()
  const shopifyConnectionFlowCompleted = createTracker(
    CreatorEvent.SHOPIFY_CONNECTION_FLOW_COMPLETED
  )

  useEffect(() => {
    if (!visible || !type) {
      return
    }
    if (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
      } else {
        if (isShopifyFixEnabled) {
          addNewModule(type)
        }
      }
    }
  }, [visible, type, ryeStores])

  // TODO: this callback references `stores` instead of `ryeStores`. This is potentially a bug
  const onSubmitRyeDomainCallback = useCallback(() => {
    const success = true
    const from = 'Modules page'
    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': true
        })
    setVisibleRyeShopifyModal(true)
    setRyeStep(RYE_MODAL_STEPS.LOGIN_SUCCESS)
  }, [stores?.length])
  return {
    ryeStep,
    setRyeStep,
    setVisibleRyeShopifyModal,
    setShowRyeShopifyInputModal,
    handleRyeLoginCallback,
    visibleRyeShopifyModal,
    connectToRyeStore,
    showRyeShopifyInputModal,
    onSubmitRyeDomainCallback
  }
}
