import LinkButton from '@/components/LinkButton'
import ExerciseTags from '@/components/Tags/ExerciseTags'
import { useSetPageTitle } from '@/utils'
import usePrependNavbar from '@/views/Navbar/usePrependNavbar'
import { Button, ButtonGroup, Spinner, Tag } from '@blueprintjs/core'
import { css } from '@emotion/css'
import useAuthIdentity from '@inject/graphql/auth'
import type { Exercise } from '@inject/graphql/fragment-types'
import type { VariablesOf } from '@inject/graphql/graphql'
import { StartExercise, StopExercise } from '@inject/graphql/mutations'
import useExercisesSubscription from '@inject/graphql/utils/useExercisesSubscription'
import Container from '@inject/shared/components/Container'
import type { FC } from 'react'
import { useClient } from 'urql'
import { exerciseClass } from '../trainee'

const index = css`
  display: flex;
  flex-direction: column;
  justify-content: center;
`

const ExerciseComponent: FC<{ exercise: Exercise; allowStart?: boolean }> = ({
  exercise,
  allowStart,
}) => {
  const client = useClient()

  return (
    <div className={exerciseClass}>
      <h3>{exercise.name}</h3>
      {/* <p>{exercise.description}</p> */}
      <p>Duration: {exercise.config.exerciseDuration} minutes</p>
      <ButtonGroup style={{ float: 'right' }} large outlined>
        <LinkButton
          button={{
            text: exercise.finished ? 'Open' : 'Instruct',
            icon: exercise.finished ? 'folder-shared-open' : 'zoom-in',
            minimal: true,
            title: 'Enter exercise',
            intent: 'primary',
          }}
          link={[
            '/instructor/:exerciseId/select',
            {
              params: { exerciseId: exercise.id },
            },
          ]}
        />
        {allowStart && (
          <Button
            icon='play'
            style={{ float: 'right' }}
            onClick={() => {
              client
                .mutation<unknown, VariablesOf<typeof StartExercise>>(
                  StartExercise,
                  {
                    id: exercise.id,
                  }
                )
                .then()
            }}
            title='Start exercise'
            intent='primary'
          >
            Start
          </Button>
        )}
        {exercise.running && (
          <Button
            icon='stop'
            style={{ float: 'right' }}
            onClick={() => {
              client
                .mutation<unknown, VariablesOf<typeof StopExercise>>(
                  StopExercise,
                  {
                    id: exercise.id,
                  }
                )
                .then()
            }}
            title='Stop exercise'
            intent='primary'
          >
            Stop
          </Button>
        )}
      </ButtonGroup>
      <ExerciseTags finished={exercise.finished} running={exercise.running} />
    </div>
  )
}

const Index = () => {
  useSetPageTitle('Instructor')
  const { isStaff } = useAuthIdentity()
  const [{ data, fetching }] = useExercisesSubscription()
  const active = data?.exercises.filter(exercise => exercise.running) || []
  const paused =
    data?.exercises.filter(
      exercise => !exercise.running && !exercise.finished
    ) || []
  const archived =
    data?.exercises.filter(
      exercise => !exercise.running && exercise.finished
    ) || []
  const element = usePrependNavbar(
    <LinkButton
      button={{
        minimal: true,
        text: 'Switch to Trainee',
        icon: 'person',
      }}
      link={['/trainee', { replace: true }]}
    />
  )

  return (
    <Container className={index}>
      {isStaff && element}
      <h1>
        Select your exercise <Tag round>Instructor</Tag>
      </h1>
      <p>Manage and oversee exercise execution</p>
      {active.length > 0 && (
        <>
          <h2>Active exercises {fetching && <Spinner />}</h2>
          {active.map(exercise => (
            <ExerciseComponent exercise={exercise} key={exercise.id} />
          ))}
        </>
      )}
      {paused.length > 0 && (
        <>
          <h2>Paused exercises {fetching && <Spinner />}</h2>
          {paused.map(exercise => (
            <ExerciseComponent
              exercise={exercise}
              key={exercise.id}
              allowStart={active.length === 0}
            />
          ))}
        </>
      )}
      {archived.length > 0 && (
        <>
          <h2>Archived exercises</h2>
          {archived.map(exercise => (
            <ExerciseComponent exercise={exercise} key={exercise.id} />
          ))}
        </>
      )}
      {!active && !archived && (
        <p>
          You haven&apos;t been assigned to any exercise yet or your exercise
          hasn&apos;t been started yet.
        </p>
      )}
    </Container>
  )
}

export default Index
