import { toggleTeam, useTeamStateMap } from '@/clientsettings/vars/teams'
import TeamLabel from '@/components/TeamLabel'
import { useNavigate } from '@/router'
import { Button, Checkbox, Divider, NonIdealState } from '@blueprintjs/core'
import { css } from '@emotion/css'
import Reloader from '@inject/graphql/components/Reloader'
import { Fragment, useEffect, useMemo } from 'react'
import useTeamStateValidator from './useTeamStateValidator'

const hideLast = css`
  &:last-child {
    display: none;
  }
`

const padRight = css`
  padding-right: 1rem;
  width: 100%;
  height: 100%;
`

const SelectorPage = () => {
  const validator = useTeamStateValidator()
  const teamStateMap = useTeamStateMap()
  const nav = useNavigate()
  const teamStates = useMemo(
    () => Object.values(teamStateMap ?? {}) || [],
    [teamStateMap]
  )
  useEffect(() => {
    validator()
  }, [validator])

  if (teamStates.length === 0) {
    return (
      <NonIdealState
        icon='low-voltage-pole'
        title='No exercise running'
        description='Please wait for administrator to start an exercise'
        action={<Reloader onRefetch={validator} />}
      />
    )
  }

  return (
    <div className={padRight}>
      <div
        style={{
          width: '100%',
          display: 'flex',
          justifyContent: 'space-between',
          marginLeft: '0.5rem',
          paddingTop: '0.25rem',
        }}
      >
        <h4>Team Selection</h4>
        <Reloader minimal onRefetch={validator} />
      </div>
      <Divider />
      <div>
        {teamStates.map(teamState => (
          <Fragment key={teamState.team.id}>
            <Checkbox
              onChange={() => {
                toggleTeam(teamState.team.id)
              }}
              checked={teamState.show}
              alignIndicator='right'
              inline={false}
              labelElement={
                <TeamLabel
                  teamId={teamState.team.id}
                  teamName={teamState.team.name}
                  teamRole={teamState.team.role}
                  exerciseName={teamState.team.exercise.name}
                  inactive={teamState.inactive}
                />
              }
              disabled={false}
            />
            <Divider className={hideLast} />
          </Fragment>
        ))}
      </div>
      <Button
        intent='primary'
        disabled={teamStates.filter(teamState => teamState.show).length === 0}
        icon='key-enter'
        fill
        onClick={() => {
          nav('/instructor/:exerciseId', {
            params: {
              exerciseId: teamStates[0].team.exercise.id,
            },
          })
        }}
      >
        Confirm selection
      </Button>
    </div>
  )
}

export default SelectorPage
