import { useNavigate, useParams } from '@/router'
import { NonIdealState } from '@blueprintjs/core'
import { useGetExerciseChannelsSuspenseQuery } from '@inject/graphql/queries/GetExerciseChannels.generated'
import ErrorMessage from '@inject/shared/components/ErrorMessage'
import { useEffect } from 'react'

const Page = () => {
  const nav = useNavigate()
  const { exerciseId, teamId } = useParams('/instructor/:exerciseId/:teamId')
  const { data, error } = useGetExerciseChannelsSuspenseQuery({
    variables: { exerciseId },
  })

  useEffect(() => {
    const infoChannelId = data?.exerciseChannels?.find(
      channel => channel?.type === 'INFO'
    )?.id
    if (infoChannelId) {
      nav('/instructor/:exerciseId/:teamId/:channelId/info', {
        params: {
          exerciseId,
          teamId,
          channelId: infoChannelId,
        },
      })
    }
  }, [data?.exerciseChannels, exerciseId, nav, teamId])

  if (error) {
    return (
      <ErrorMessage>
        <h1>Error occurred!</h1>
        <p>{error.message}</p>
      </ErrorMessage>
    )
  }

  return (
    <NonIdealState
      icon='search'
      title='No channel selected'
      description='Select a channel to interact with'
    />
  )
}

export default Page
