import LinkButton from '@/components/LinkButton'
import { useNavigate } from '@/router'
import { useSetPageTitle } from '@/utils'
import usePrependNavbar from '@/views/Navbar/usePrependNavbar'
import { Button, ButtonGroup, Classes, 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'

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

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

  return (
    <div
      className={css`
        padding: 1rem;
        padding-top: 0;
        margin: 0.5rem;
        border: 1px solid rgba(0, 0, 0, 0.2);
        border-radius: 0.5rem;
        .${Classes.DARK} & {
          border-color: rgba(255, 255, 255, 0.2);
        }

        box-shadow: rgba(0, 0, 0, 0.1) 0 0.125rem 0.5rem;
        transition: box-shadow 0.2s ease;
      `}
    >
      <h3>{exercise.name}</h3>
      {/* <p>{exercise.description}</p> */}
      <p>Duration: {exercise.config.exerciseDuration} minutes</p>
      <ButtonGroup style={{ float: 'right' }} large outlined>
        <Button
          icon={exercise.finished ? 'folder-shared-open' : 'zoom-in'}
          style={{ float: 'right' }}
          onClick={() =>
            nav('/instructor/:exerciseId/select', {
              params: { exerciseId: exercise.id },
            })
          }
          title='Enter exercise'
          intent='primary'
        >
          {exercise.finished && 'Open'}
          {!exercise.finished && 'Instruct'}
        </Button>
        {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>
      <div
        className={css`
          display: flex;
          gap: 0.5rem;
        `}
      >
        {exercise.running && (
          <Tag intent='success' round large>
            Running
          </Tag>
        )}
        {exercise.finished && (
          <Tag intent='success' round large>
            Finished
          </Tag>
        )}
        {!exercise.running && !exercise.finished && (
          <Tag intent='warning' round large>
            Paused
          </Tag>
        )}
      </div>
    </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
