import { useEffect } from 'react'
import Intercom from '@intercom/messenger-js-sdk'

import { FLAGS, useFeatureIsOn } from '@komi-app/flags-sdk'

import config from '../config'

import { useUserAccountDetails } from './useUserAccountDetails'
import { useTalentProfileCategory } from './useTalentProfileCategory'

import '../styles/component/intercom-messenger.scss'

export function useIntercomMessengerWidget() {
  const isIntercomEnabled = useFeatureIsOn(FLAGS.FEAT_SB_1244_INTERCOM_WIDGET)

  const user = useUserAccountDetails()
  const { name: categoryName } = useTalentProfileCategory() || {}

  useEffect(() => {
    if (isIntercomEnabled && user && config.intercom.appId) {
      Intercom({
        app_id: config.intercom.appId,
        user_id: user.id?.toString(),
        name: user.fullname,
        email: user.email,
        created_at: user.createdAt,
        category: categoryName
      })
    }
  }, [isIntercomEnabled, user])
}
