import { useParams } from '@/router'
import getPopupProps from '@/views/TraineeView/getPopupProps'
import type { ActionLog, Overlay } from '@inject/graphql/fragment-types'
import '@inject/graphql/urql/events.d.ts'
import useActionLogSubscriptionTrainee from '@inject/graphql/utils/Subscriptions/trainee'
import { usePopupContext } from '@inject/shared/popup/PopupContext'
import { useEventListener } from 'ahooks'
import { useCallback } from 'react'
import { Outlet } from 'react-router-dom'

const Layout = () => {
  const { exerciseId, teamId } = useParams('/trainee/:exerciseId/:teamId')
  useActionLogSubscriptionTrainee({
    exerciseId,
    teamId,
  })

  const { showPopup } = usePopupContext()
  const handleOverlay = useCallback(
    (actionLog: ActionLog, overlay: Overlay | null) => {
      if (!overlay) {
        return
      }

      showPopup({
        duration: overlay.duration,
        ...getPopupProps(actionLog),
      })
    },
    [showPopup]
  )
  useEventListener('actionLogEvent', e => {
    const { actionLog, eventType } = e.detail

    if (eventType !== 'CREATE') {
      return
    }

    switch (actionLog.details.__typename) {
      case 'InjectDetailsType':
      case 'CustomInjectDetailsType':
      case 'EmailType':
        handleOverlay(actionLog, actionLog.details.overlay)
        break
      case 'TeamQuestionnaireStateType':
        handleOverlay(actionLog, actionLog.details.questionnaire.overlay)
        break
      default:
        break
    }
  })

  return <Outlet />
}

export default Layout
