import useMilestoneStates from '@/analyst/dataHooks/useMilestoneStates'
import useMilestones from '@/analyst/dataHooks/useMilestones'
import type { MilestoneState } from '@inject/graphql/fragments/MilestoneState.generated'
import type { Dispatch, FC } from 'react'
import type { selectedReducerActionProps } from '../Overview/selectedReducer'
import AllTeamsMilestoneCard from './AllTeamsMilestoneCard'
import MilestoneCard from './MilestoneCard'

interface MilestoneCardsProps {
  teamId: string | undefined
  selectedState?: MilestoneState
  selectedDispatch: Dispatch<selectedReducerActionProps>
}

const MilestoneCards: FC<MilestoneCardsProps> = ({
  teamId,
  selectedState,
  selectedDispatch,
}) => {
  const milestoneStates = useMilestoneStates()
  const milestones = useMilestones()

  return (
    <div
      style={{
        display: 'flex',
        flexWrap: 'wrap',
        justifyContent: 'center',
        gap: '0.5rem',
      }}
    >
      {teamId === undefined
        ? milestones
            .sort((a, b) => (a.name > b.name ? 1 : -1))
            .map(milestone => (
              <AllTeamsMilestoneCard
                key={milestone.id}
                milestone={milestone}
                isSelected={selectedState?.milestone.id === milestone.id}
                selectedDispatch={selectedDispatch}
              />
            ))
        : milestoneStates
            .filter(milestoneState =>
              teamId === undefined
                ? true
                : milestoneState.teamIds &&
                  milestoneState.teamIds.includes(teamId)
            )
            .sort((a, b) => (a.milestone.name > b.milestone.name ? 1 : -1))
            .map(milestoneState => (
              <MilestoneCard
                key={milestoneState.milestone.id}
                milestoneState={milestoneState}
                isSelected={selectedState?.id === milestoneState.id}
                selectedDispatch={selectedDispatch}
              />
            ))}
    </div>
  )
}

export default MilestoneCards
