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

const Page = () => {
  const nav = useNavigate()
  const { exerciseId, teamId } = useParams('/trainee/:exerciseId/:teamId')
  const [{ data, error }] = useTypedQuery({
    query: GetExerciseChannels,
    variables: {
      exerciseId,
    },
    context: useMemo(
      () => ({
        suspense: true,
      }),
      []
    ),
  })

  useEffect(() => {
    const infoChannelId = data?.exerciseChannels?.find(
      channel => channel?.type === 'INFO'
    )?.id
    if (infoChannelId) {
      nav('/trainee/: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
