import useMilestoneStates from '@/analyst/dataHooks/useMilestoneStates'
import MilestoneDescription from '@/components/Description/MilestoneDescription'
import { Callout, Classes, H6 } from '@blueprintjs/core'
import type { Milestone } from '@inject/graphql/fragment-types'
import type { Dispatch, FC } from 'react'
import { useContext } from 'react'
import ExerciseContext from '../ExerciseContext'
import type { selectedReducerActionProps } from '../Overview/selectedReducer'
import { getIntent } from '../utilities'
import { milestoneCard } from './MilestoneCard'

interface AllTeamsMilestoneCardProps {
  isSelected?: boolean
  milestone: Milestone
  selectedDispatch: Dispatch<selectedReducerActionProps>
}

const AllTeamsMilestoneCard: FC<AllTeamsMilestoneCardProps> = ({
  isSelected,
  milestone,
  selectedDispatch,
}) => {
  const { exercise } = useContext(ExerciseContext)
  const milestoneStates = useMilestoneStates()

  const filteredMilestoneStates = milestoneStates.filter(
    milestoneState => milestoneState.milestone.id === milestone.id
  )

  const progress =
    filteredMilestoneStates.filter(milestoneState => milestoneState.reached)
      .length / filteredMilestoneStates.length

  const teamIdsReached = new Set()
  filteredMilestoneStates.forEach(filteredMilestoneState => {
    if (filteredMilestoneState.reached) {
      filteredMilestoneState.teamIds?.forEach(teamId =>
        teamIdsReached.add(teamId)
      )
    }
  })

  return (
    <Callout
      className={milestoneCard(isSelected)}
      intent={getIntent(progress)}
      icon={null}
      onClick={() =>
        selectedDispatch({
          type: 'selectMilestones',
          milestoneState: filteredMilestoneStates[0],
        })
      }
    >
      <MilestoneDescription
        milestone={milestone}
        getChildren={displayName => <H6>{displayName}</H6>}
      />
      <span className={Classes.TEXT_SMALL}>
        {`reached by ${teamIdsReached.size}/${exercise.teams.length}`}
      </span>
    </Callout>
  )
}

export default AllTeamsMilestoneCard
