import {
  Boundary,
  ButtonGroup,
  Classes,
  OverflowList,
  Popover,
} from '@blueprintjs/core'
import type { MilestoneState, Team } from '@inject/graphql/fragment-types'
import type { Dispatch, FC } from 'react'
import { useContext, useState } from 'react'
import ExerciseContext from '../ExerciseContext'
import type { selectedReducerActionProps } from '../Overview/selectedReducer'
import MilestoneCards from './MilestoneCards'
import Title from './Title'

interface MilestonesProps {
  selectedState?: MilestoneState
  selectedDispatch: Dispatch<selectedReducerActionProps>
}

const Milestones: FC<MilestonesProps> = ({
  selectedState,
  selectedDispatch,
}) => {
  const { exercise } = useContext(ExerciseContext)

  const [selectedId, setSelectedId] = useState<string | undefined>()

  const handleClick = (item: Team | undefined) => () => {
    setSelectedId(item?.id)
  }

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

  const visibleItemRenderer = (item: Team | undefined) => (
    <Title
      key={item?.id || 'AllTeamsTab'}
      team={item}
      onClick={handleClick(item)}
      active={selectedId === item?.id}
    />
  )

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

      <MilestoneCards
        teamId={selectedId}
        selectedState={selectedState}
        selectedDispatch={selectedDispatch}
      />
    </div>
  )
}

export default Milestones
