import { Colors, Radio, RadioGroup } from '@blueprintjs/core'
import { css } from '@emotion/css'
import type { RadioQuestionDetails } from '@inject/graphql/fragment-types'
import { breakWord } from '@inject/shared/css/textOverflow'
import { type FC } from 'react'
import RenderedContent from '../RenderedContent'
import type { QuestionProps } from './types'

const highlightCorrect = (correct: boolean) => css`
  padding-bottom: 0.2rem;
  border-bottom: 0.2rem solid ${correct ? Colors.GREEN5 : 'transparent'};
`

const RadioButtonQuestion: FC<QuestionProps> = ({
  type,
  question,
  answer,
  disabled,
  onChange,
  inInstructor,
  teamId,
}) => {
  const details = question.details as RadioQuestionDetails
  const { labels: labelsString, max, correct } = details

  const labels = labelsString
    ? labelsString.split(',').map(label => label.trim())
    : [...Array(max).keys()].map(index => (index + 1).toString())

  return (
    <RadioGroup
      inline
      label={
        <RenderedContent
          className={breakWord}
          teamId={teamId}
          inInstructor={inInstructor}
          renderedContent={question.content.rendered}
        />
      }
      selectedValue={answer}
      onChange={
        onChange ? event => onChange(event.currentTarget.value) : () => {}
      }
    >
      {labels.map((label, index) => (
        <Radio
          disabled={disabled || type === 'reviewing'}
          className={
            type === 'reviewing'
              ? highlightCorrect(labels.indexOf(label) + 1 === correct)
              : undefined
          }
          key={label}
          value={(index + 1).toString()}
          label={label}
        />
      ))}
    </RadioGroup>
  )
}

export default RadioButtonQuestion
