import TooltipLabel from '@/editor/Tooltips/TooltipLabel'
import { QUESTIONNAIRE_QUESTION_FORM } from '@/editor/assets/pageContent/injectSpecification'
import type { OptionProps } from '@blueprintjs/core'
import {
  Button,
  ControlGroup,
  Icon,
  Radio,
  RadioGroup,
} from '@blueprintjs/core'
import type { FC } from 'react'
import { memo, useCallback, useEffect, useState } from 'react'
import CustomLabelForm from './CustomLabelForm'

interface QuestionCustomLabelsProps {
  labels: string
  correct: number
  onLabelsChange: (value: string) => void
  onCorrectChange: (value: number) => void
}

const QuestionCustomLabels: FC<QuestionCustomLabelsProps> = ({
  labels,
  correct,
  onLabelsChange,
  onCorrectChange,
}) => {
  const [options, setOptions] = useState<OptionProps[]>([])

  useEffect(() => {
    if (!labels) {
      setOptions([])
    } else {
      setOptions(
        labels.split(', ').map((label, index) => ({
          label: label,
          value: index + 1,
        }))
      )
    }
  }, [labels])

  const onAdd = useCallback(
    (answer: string) => {
      if (!labels) {
        onLabelsChange(answer)
      } else {
        onLabelsChange(`${labels}, ${answer}`)
      }
    },
    [labels]
  )

  const onDelete = useCallback(
    (option: OptionProps) => {
      const value = Number(option.value)
      if (correct === value) {
        onCorrectChange(1)
      }
      if (correct > value) {
        onCorrectChange(correct - 1)
      }
      onLabelsChange(
        [...options.slice(0, value - 1), ...options.slice(value)]
          .map((option: OptionProps) => option?.label || '')
          .join(', ')
      )
    },
    [correct, options]
  )

  return (
    <TooltipLabel label={QUESTIONNAIRE_QUESTION_FORM.answers}>
      <RadioGroup onChange={() => {}}>
        {options.length > 0 ? (
          options.map(option => (
            <ControlGroup key={option.value} style={{ display: 'flex' }}>
              <Radio
                label={option.label}
                value={option.value}
                checked={correct === option.value}
                onClick={e => onCorrectChange(Number(e.currentTarget.value))}
                onChange={() => {}}
                style={{ flexGrow: '1' }}
              />
              <Button icon='trash' minimal onClick={() => onDelete(option)} />
            </ControlGroup>
          ))
        ) : (
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              padding: '1rem 0',
            }}
          >
            <Icon icon='disable' style={{ marginRight: '0.5rem' }} />
            <span>No answers specified.</span>
          </div>
        )}
      </RadioGroup>
      <CustomLabelForm onAdd={(answer: string) => onAdd(answer)} />
    </TooltipLabel>
  )
}

export default memo(QuestionCustomLabels)
