import { toggleTeam, useTeamStateMap } from '@/clientsettings/vars/teams'
import TeamLabel from '@/components/TeamLabel'
import {
  Button,
  Checkbox,
  Dialog,
  DialogBody,
  DialogFooter,
  Divider,
} from '@blueprintjs/core'
import Reloader from '@inject/graphql/components/Reloader'
import { useSubscriptionContext } from '@inject/graphql/context/SubscriptionContext'
import { dialog, dialogBody } from '@inject/shared/css/dialog'
import type { FC } from 'react'
import { useEffect, useMemo, useState } from 'react'
import TeamButton from './TeamButton'
import useTeamStateValidator from './useTeamStateValidator'

interface InstructorTeamSelectorProps {
  hideLabel?: boolean
  teamId: string | undefined
}

const InstructorTeamSelector: FC<InstructorTeamSelectorProps> = ({
  hideLabel,
  teamId,
}) => {
  const validator = useTeamStateValidator()
  const teamStateMap = useTeamStateMap()
  const { subscribeTeam } = useSubscriptionContext()

  const [openSelector, setOpenSelector] = useState(false)

  const teamStates = useMemo(
    () => Object.values(teamStateMap ?? {}) || [],
    [teamStateMap]
  )
  const selectedTeamStates = useMemo(
    () => teamStates.filter(teamState => teamState.show),
    [teamStates]
  )

  useEffect(() => {
    validator()
  }, [])

  // todo: add handler to accessing teams outside of said range
  useEffect(
    () => subscribeTeam(selectedTeamStates.map(teamState => teamState.team.id)),
    [subscribeTeam, selectedTeamStates]
  )

  useEffect(() => {
    if (selectedTeamStates.length === 0) {
      setOpenSelector(true)
    }
  }, [selectedTeamStates.length])

  return (
    <>
      <Button
        active={openSelector}
        icon='team'
        alignText='left'
        fill
        minimal
        text={!hideLabel && 'Select teams'}
        title='Select teams'
        onClick={() => setOpenSelector(!openSelector)}
      />
      {selectedTeamStates.map(teamState => (
        <TeamButton
          key={teamState.team.id}
          hideLabel={hideLabel}
          selectedTeamId={teamId}
          teamState={teamState}
        />
      ))}

      <Dialog
        className={dialog}
        isOpen={openSelector}
        onClose={() => setOpenSelector(false)}
        canOutsideClickClose={false}
        icon='team'
        title='Select teams'
      >
        <DialogBody className={dialogBody}>
          {teamStates.map((teamState, i) => (
            <div key={teamState.team.id}>
              <Checkbox
                key={teamState.team.id}
                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}
              />
              {i < teamStates.length - 1 && <Divider />}
            </div>
          ))}
        </DialogBody>
        <DialogFooter
          actions={
            <Button
              onClick={() => setOpenSelector(false)}
              icon='tick'
              intent='primary'
              text='Confirm'
            />
          }
        >
          <Reloader onRefetch={validator} minimal />
        </DialogFooter>
      </Dialog>
    </>
  )
}

export default InstructorTeamSelector
