import ExerciseContext from '@/analyst/ExerciseContext'
import NavigationBar from '@/analyst/NavigationBar'
import { DUMMY_EXERCISE } from '@/analyst/utilities'
import { useParams } from '@/router'
import { NonIdealState } from '@blueprintjs/core'
import { useTypedQuery } from '@inject/graphql/graphql'
import { GetExercise } from '@inject/graphql/queries'
import useActionLogSubscriptionInstructor from '@inject/graphql/utils/Subscriptions/instructor'
import CenteredSpinner from '@inject/shared/components/CenteredSpinner'
import ErrorMessage from '@inject/shared/components/ErrorMessage'
import { useMemo } from 'react'
import { Outlet } from 'react-router-dom'

const Layout = () => {
  const { exerciseId } = useParams('/analyst/:exerciseId')

  const [{ data, fetching: loading, error }] = useTypedQuery({
    query: GetExercise,
    variables: { exerciseId },
  })
  useActionLogSubscriptionInstructor({ exerciseId })

  const exerciseContextValue = useMemo(
    () => ({
      exercise: data?.exerciseId || DUMMY_EXERCISE,
    }),
    [data?.exerciseId]
  )

  // TODO: use suspense instead (test when switching exercises)
  if (loading) {
    return <CenteredSpinner />
  }
  if (error) {
    return (
      <ErrorMessage>
        <h1>Error occurred!</h1>
        <p>{error.message}</p>
      </ErrorMessage>
    )
  }
  if (!data || !data.exerciseId) {
    return (
      <NonIdealState
        icon='low-voltage-pole'
        title='No data'
        description='Please wait for the data to come in'
      />
    )
  }

  return (
    <ExerciseContext.Provider value={exerciseContextValue}>
      <NavigationBar>
        <Outlet />
      </NavigationBar>
    </ExerciseContext.Provider>
  )
}

export default Layout
