import { useAnalytics } from 'hooks/useAnalytics'
import { FLAGS, useFeatureIsOn } from '@komi-app/flags-sdk'
import {
  BaseItem,
  TalentProfileModule
} from 'models/talent/talent-profile-module.model'
import { CreatorEvent, useCreatorTracking } from '@komi-app/analytics-sdk'
import { SEGMENT_EVENTS } from 'constants/segment'

export const getItemId = <T>(module: TalentProfileModule<T>) =>
  (module.items[0] as BaseItem).id || ''

export const useAnalyticsCompleteItemCreation = () => {
  const useAnalyticsSDK = useFeatureIsOn(FLAGS.USE_ANALYTICS_SDK_TALENT)
  const { sendSegmentEvent } = useAnalytics()
  const { createTracker } = useCreatorTracking()
  const completeItemCreation = createTracker(
    CreatorEvent.COMPLETED_ITEM_CREATION
  )

  const trackCompleteAddingItemToModule = <T>(
    module: TalentProfileModule<T>
  ) => {
    if (module.items.length === 0) {
      return
    }

    const moduleId = module.id
    const itemId = getItemId(module)

    if (!moduleId) {
      return
    }

    if (useAnalyticsSDK) {
      completeItemCreation({
        moduleId,
        itemId
      })
    } else {
      sendSegmentEvent(SEGMENT_EVENTS.COMPLETED_ITEM_CREATION, {
        'Module ID': moduleId,
        'Item ID': itemId
      })
    }
  }

  return { trackCompleteAddingItemToModule }
}
