import { Button, ButtonGroup, Card } from '@blueprintjs/core'
import { notify } from '@inject/shared/notification/engine'
import { range } from 'lodash'
import type { FC } from 'react'
import { memo, useCallback, useEffect, useState } from 'react'
import { deleteQuestionnaireQuestion } from '../../indexeddb/operations'
import { type QuestionnaireQuestion } from '../../indexeddb/types'
import QuestionnaireQuestionForm from './QuestionnaireQuestionForm'

interface QuestionnaireQuestionProps {
  questionnaireQuestion: QuestionnaireQuestion
}

const QuestionnaireQuestionItem: FC<QuestionnaireQuestionProps> = ({
  questionnaireQuestion,
}) => {
  const [answers, setAnswers] = useState<string[]>([])

  const handleDeleteButton = useCallback(
    async (question: QuestionnaireQuestion) => {
      try {
        await deleteQuestionnaireQuestion(question.id)
      } catch (error) {
        notify(
          `Failed to delete question '${question.text}': ${error}`,
          JSON.stringify(error),
          {
            intent: 'danger',
          }
        )
      }
    },
    []
  )

  useEffect(() => {
    setAnswers(
      questionnaireQuestion.labels
        ? questionnaireQuestion.labels.split(', ')
        : range(1, questionnaireQuestion.max + 1).map(value => value.toString())
    )
  }, [questionnaireQuestion])

  return (
    <Card
      style={{ display: 'flex', flexDirection: 'column', alignItems: 'start' }}
    >
      <div
        style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          width: '100%',
        }}
      >
        <span style={{ flexGrow: 1 }}>{questionnaireQuestion.text}</span>
        <ButtonGroup>
          <QuestionnaireQuestionForm
            questionnaireQuestion={questionnaireQuestion}
            questionnaireId={questionnaireQuestion.questionnaireId}
            buttonProps={{
              minimal: true,
              icon: 'edit',
              style: { marginRight: '1rem' },
            }}
          />
          <Button
            minimal
            icon='cross'
            onClick={() => handleDeleteButton(questionnaireQuestion)}
          />
        </ButtonGroup>
      </div>
      <ol>
        {answers.map((answer, i) => (
          <li
            key={i}
            style={{
              fontWeight:
                questionnaireQuestion.correct === i + 1 ? 'bold' : 'normal',
            }}
          >
            {answer}
          </li>
        ))}
      </ol>
    </Card>
  )
}

export default memo(QuestionnaireQuestionItem)
