import type { QuestionReview } from '@/components/Questionnaire/types'
import type { ButtonProps } from '@blueprintjs/core'
import { Button, CardList, Popover } from '@blueprintjs/core'
import { css } from '@emotion/css'
import type {
  MilestoneState,
  TeamQuestionnaireState,
} from '@inject/graphql/fragment-types'
import { useCallback, useMemo, useState, type FC } from 'react'
import MilestoneIndicator from '../InstructorMilestones/MilestoneIndicator'

const contentWrapper = css`
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  padding: 1rem;
  align-items: end;
`

interface ReviewButtonProps {
  status: TeamQuestionnaireState['status']
  questionReview: QuestionReview
  setQuestionReview: (questionReview: QuestionReview) => void
  milestones: MilestoneState[]
  teamId: string
}

const ReviewButton: FC<ReviewButtonProps> = ({
  status,
  milestones,
  teamId,
  questionReview,
  setQuestionReview,
}) => {
  const [open, setOpen] = useState(false)

  const updateReview = useCallback(() => {
    setQuestionReview({ ...questionReview, done: true })
  }, [questionReview, setQuestionReview])

  const { disabled, title } = useMemo<ButtonProps>(() => {
    switch (status) {
      case 'UNSENT': // fallthrough
      case 'SENT':
        return { disabled: true, title: 'Answers have not been submitted yet' }
      case 'ANSWERED': // fallthrough
      case 'REVIEWED':
        return { disabled: false, title: undefined }
      default:
        throw new Error(`Unknown status: ${status}`)
    }
  }, [status])

  return (
    <Popover
      isOpen={open}
      content={
        <div className={contentWrapper}>
          <CardList bordered={false} compact>
            {milestones.map(milestone => (
              <MilestoneIndicator
                milestone={milestone}
                key={milestone.milestone.id}
                teamId={teamId}
              />
            ))}
          </CardList>
          <div>
            <Button
              icon='tick'
              onClick={() => {
                setOpen(false)
                updateReview()
              }}
            >
              Done
            </Button>
          </div>
        </div>
      }
      placement='right'
      onClose={() => setOpen(false)}
    >
      <Button
        active={open}
        disabled={disabled}
        title={title}
        onClick={() => setOpen(prev => !prev)}
      >
        Review
      </Button>
    </Popover>
  )
}

export default ReviewButton
