import { getTitle } from '@/actionlog/InjectMessage/utils'
import { useNavTo } from '@/instructor/InstructorTodoLog/LogItem'
import { useParams } from '@/router'
import { useSetPageTitle, useStaffBoundary } from '@/utils'
import InstructorView from '@/views/InstructorView'
import useActionLogSubscriptionInstructor from '@inject/graphql/utils/Subscriptions/instructor'
import CenteredSpinner from '@inject/shared/components/CenteredSpinner'
import { callSystemNotification } from '@inject/shared/notification/system'
import { useEventListener } from 'ahooks'

export const Pending = () => <CenteredSpinner />

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

  useActionLogSubscriptionInstructor({
    exerciseId,
  })

  const navTo = useNavTo('none')
  useEventListener('actionLogEvent', e => {
    if (
      e.detail.actionLog.requiresAttention &&
      e.detail.actionLog.team.subscribed
    ) {
      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
