import {
  Boundary,
  ButtonGroup,
  Classes,
  OverflowList,
  Popover,
} from '@blueprintjs/core'
import type { Team } from '@inject/graphql/fragments/Team.generated'
import { useContext } from 'react'
import ExerciseContext from '../../ExerciseContext'
import TabButton from '../../OverflowTabs/TabButton'
import SelectedContext from '../SelectedContext'

const TeamSelector = () => {
  const { exercise } = useContext(ExerciseContext)
  const { selectedReducer } = useContext(SelectedContext)
  const [selectedState, selectedDispatch] = selectedReducer

  const handleClick = (item: Team | undefined) => () =>
    selectedDispatch({ type: 'selectTeam', team: item })

  const overflowRenderer = (overflowItems: (Team | undefined)[]) => (
    <div style={{ marginLeft: 'auto' }}>
      <Popover
        content={
          <ButtonGroup vertical style={{ padding: 8 }}>
            {overflowItems.map(item => (
              <TabButton
                key={item?.id || 'AllTeamsTab'}
                active={selectedState.team?.id === item?.id}
                onClick={handleClick(item)}
              >
                {item?.name || 'All teams'}
              </TabButton>
            ))}
          </ButtonGroup>
        }
        position='bottom-left'
      >
        <span className={Classes.BREADCRUMBS_COLLAPSED} style={{ margin: 4 }} />
      </Popover>
    </div>
  )

  const visibleItemRenderer = (item: Team | undefined) => (
    <TabButton
      key={item?.id || 'AllTeamsTab'}
      active={selectedState.team?.id === item?.id}
      onClick={handleClick(item)}
    >
      {item?.name || 'All teams'}
    </TabButton>
  )

  return (
    <OverflowList
      style={{ alignItems: 'center', marginBottom: 8 }}
      collapseFrom={Boundary.END}
      items={[undefined, ...exercise.teams]}
      overflowRenderer={overflowRenderer}
      visibleItemRenderer={visibleItemRenderer}
    />
  )
}

export default TeamSelector
