import { getTitle } from '@/actionlog/InjectMessage/utils'
import { teamStateMap } from '@/clientsettings/vars/teams'
import { useNavTo } from '@/instructor/InstructorTodoLog/LogItem'
import { useNavigate, useParams } from '@/router'
import { useSetPageTitle, useStaffBoundary } from '@/utils'
import InstructorView from '@/views/InstructorView'
import { callSystemNotification } from '@inject/shared/notification/system'
import { useEventListener } from 'ahooks'
import { useEffect } from 'react'

const Layout = () => {
  const { exerciseId, teamId } = useParams('/instructor/:exerciseId/:teamId')
  useStaffBoundary()
  useSetPageTitle('Instructor')

  const nav = useNavigate()
  useEffect(() => {
    if (Object.entries(teamStateMap()).every(teamState => !teamState[1].show)) {
      nav('/instructor')
    }
  })
  const navTo = useNavTo()
  useEventListener('actionLogEvent', e => {
    console.log('notify event?: ', e.detail.actionLog.requiresAttention)
    if (
      e.detail.actionLog.requiresAttention &&
      Object.entries(teamStateMap()).some(
        teamState =>
          e.detail.actionLog.team.id === teamState[1].team.id &&
          teamState[1].show
      )
    ) {
      callSystemNotification(
        `[${e.detail.actionLog.team.name}] There is a response that requires attention`,
        {
          body: getTitle(e.detail.actionLog),
          requireInteraction: false,
        }
      ).then(n => {
        n?.addEventListener('click', () => {
          window.focus()
          navTo(e.detail.actionLog)
        })
      })
    }
  })

  // todo: implement manager to be a :teamIds dependant

  return <InstructorView exerciseId={exerciseId} teamId={teamId} />
}

export default Layout
