import TeamLabel from '@/components/TeamLabel'
import { useNavigate } from '@/router'
import { Button, Checkbox, Classes, Divider, Tag } from '@blueprintjs/core'
import { css } from '@emotion/css'
import Reloader from '@inject/graphql/components/Reloader'
import { useTypedQuery } from '@inject/graphql/graphql'
import { SetTeamSubscribe } from '@inject/graphql/mutations.client'
import { GetExercise } from '@inject/graphql/queries'
import type { FC } from 'react'
import { Fragment } from 'react'
import { useClient } from 'urql'

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

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

const mainEl = css`
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-left: 0.5rem;
  padding-top: 0.25rem;
  min-height: 4rem;
`

const SelectorPage: FC<{ exerciseId: string }> = ({ exerciseId }) => {
  const nav = useNavigate()
  const client = useClient()

  const [{ data }, refetch] = useTypedQuery({
    query: GetExercise,
    variables: {
      exerciseId: exerciseId || '',
    },
  })
  const teamStates = data?.exerciseId.teams || []

  return (
    <div className={padRight}>
      <div className={mainEl}>
        <div>
          <span className={Classes.HEADING}>Team Selection</span>
          {data?.exerciseId.name && (
            <Tag round style={{ marginLeft: '0.5rem' }}>
              {data.exerciseId.name}
            </Tag>
          )}
        </div>
        <div>
          <Reloader minimal onRefetch={refetch} />
        </div>
      </div>
      <Divider />
      <div>
        {teamStates.map(team => (
          <Fragment key={team.id}>
            <Checkbox
              onChange={() => {
                client
                  .mutation(SetTeamSubscribe, {
                    teamId: team.id,
                    state: !team.subscribed,
                  })
                  .then()
              }}
              checked={team.subscribed}
              alignIndicator='right'
              inline={false}
              labelElement={
                <TeamLabel
                  teamId={team.id}
                  teamName={team.name}
                  teamRole={team.role}
                  exerciseName={data?.exerciseId.name}
                />
              }
              disabled={false}
            />
            <Divider className={hideLast} />
          </Fragment>
        ))}
      </div>
      <Button
        intent='primary'
        disabled={teamStates.filter(team => team.subscribed).length === 0}
        icon='key-enter'
        fill
        onClick={() => {
          nav('/instructor/:exerciseId', {
            params: {
              exerciseId,
            },
          })
        }}
      >
        Confirm selection
      </Button>
    </div>
  )
}

export default SelectorPage
