import useMilestoneStates from '@/analyst/dataHooks/useMilestoneStates'
import MilestoneDescription from '@/components/Description/MilestoneDescription'
import { Callout, Classes, H6 } from '@blueprintjs/core'
import { Flag } from '@blueprintjs/icons'
import { css } from '@emotion/css'
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'

const wrapper = css`
  display: flex;
  align-items: center;
  gap: 0.1rem;
  justify-content: center;
`

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],
        })
      }
    >
      <div className={wrapper}>
        {milestone.final && (
          <Flag style={{ padding: '0.2rem' }} title='Final milestone' />
        )}
        <MilestoneDescription
          milestone={milestone}
          getChildren={displayName => (
            <H6 style={{ margin: 0 }}>{displayName}</H6>
          )}
        />
      </div>

      <span className={Classes.TEXT_SMALL}>
        {`reached by ${teamIdsReached.size}/${exercise.teams.length}`}
      </span>
    </Callout>
  )
}

export default AllTeamsMilestoneCard
