import { Navigate, 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 { useMemo } from 'react'

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

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

  const infoChannelId = data?.exerciseChannels?.find(
    channel => channel?.type === 'INFO'
  )?.id
  if (infoChannelId) {
    return (
      <Navigate
        to='/trainee/:exerciseId/:teamId/:channelId/info'
        params={{
          exerciseId,
          teamId,
          channelId: infoChannelId,
        }}
        replace
      />
    )
  }

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

export default Page
