import React, { Dispatch, SetStateAction, useCallback, useState } from 'react'
import './quizQuestion.scss'
import CloseIcon from 'assets/icons/ico/close.svg'
import StyledIconButton from 'components/CommonKit/IconButton/StyledIconButton'
import Button from '@material-ui/core/Button'
import QuizExplanationModal from 'components/Quiz/QuizExplanationModal'
import { useI18n } from 'cozy-ui/transpiled/react/I18n'
import { Answer, UserChallenge, UserQuiz } from 'models'
import ChallengeService from 'services/challenge.service'
import QuizService from 'services/quiz.service'
import { Client, useClient } from 'cozy-client'
import { UserChallengeUpdateFlag } from 'enum/userChallenge.enum'
import { updateUserChallengeList } from 'store/challenge/challenge.actions'
import { useDispatch } from 'react-redux'

interface QuizQuestionContent {
  userChallenge: UserChallenge
  setIsCustomQuest: Dispatch<SetStateAction<boolean>>
  goBack: () => void
}

const QuizQuestionContent: React.FC<QuizQuestionContent> = ({
  userChallenge,
  setIsCustomQuest,
  goBack,
}: QuizQuestionContent) => {
  const { t } = useI18n()
  const questionIndexLocked = userChallenge.quiz.questions.findIndex(
    answer => answer.result == 0
  )
  const [userChoice, setUserChoice] = useState<string>('')
  const [openModal, setOpenModal] = useState<boolean>(false)
  const [answerIndex, setAnswerIndex] = useState<number>(0)
  const [questionIndex, setQuestionIndex] = useState<number>(
    questionIndexLocked
  )

  const client: Client = useClient()
  const dispatch = useDispatch()

  const quizService: QuizService = new QuizService(client)
  const challengeService: ChallengeService = new ChallengeService(client)

  const validateQuestion = async () => {
    const resultIndex: number = userChallenge.quiz.questions[
      questionIndex
    ].answers.findIndex(answer => answer.answerLabel === userChoice)
    const result: Answer[] = userChallenge.quiz.questions[
      questionIndex
    ].answers.filter(answer => answer.answerLabel === userChoice)
    setAnswerIndex(resultIndex)
    setOpenModal(true)
    const quizUpdated: UserQuiz = await quizService.updateUserQuiz(
      userChallenge.quiz,
      result[0].isTrue,
      questionIndex
    )
    const userChallengeUpdated: UserChallenge = await challengeService.updateUserChallenge(
      userChallenge,
      UserChallengeUpdateFlag.QUIZ_UPDATE,
      quizUpdated
    )
    dispatch(updateUserChallengeList(userChallengeUpdated))
  }

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setUserChoice(e.target.value)
  }
  const goNextQuestion = useCallback(() => {
    setUserChoice('')
    setOpenModal(false)
    if (questionIndex === userChallenge.quiz.questions.length - 1) {
      setIsCustomQuest(true)
    }
    if (questionIndex !== userChallenge.quiz.questions.length - 1) {
      setQuestionIndex(questionIndex + 1)
    }
  }, [
    questionIndex,
    setIsCustomQuest,
    setQuestionIndex,
    setUserChoice,
    setOpenModal,
    userChallenge.quiz.questions.length,
  ])

  return (
    <div className="quiz-container">
      <div className="question-container">
        <StyledIconButton
          className="btn-back"
          icon={CloseIcon}
          onClick={goBack}
        />
        <p className="index-question">{questionIndex + 1}/5</p>
        <p className="question text-18-bold">
          {userChallenge.quiz.questions[questionIndex].questionLabel}
        </p>
        {userChallenge.quiz.questions[questionIndex].answers.map(
          (answer, index) => {
            return (
              <div className="answer" key={index}>
                <input
                  type="radio"
                  id={`answer${index}`}
                  value={answer.answerLabel}
                  onChange={handleChange}
                  checked={userChoice === answer.answerLabel}
                />
                <label htmlFor={`answer${index}`} className="text-16-bold">
                  {answer.answerLabel}
                </label>
              </div>
            )
          }
        )}
      </div>
      {userChoice && (
        <Button
          aria-label={t('quiz.accessibility.button_validate')}
          onClick={validateQuestion}
          classes={{
            root: 'btn-secondary-negative',
            label: 'text-16-normal',
          }}
        >
          {t('quiz.button_validate')}
        </Button>
      )}
      {openModal && (
        <QuizExplanationModal
          open={openModal}
          answerIndex={answerIndex}
          question={userChallenge.quiz.questions[questionIndex]}
          goNext={goNextQuestion}
          handleCloseClick={() => setOpenModal(false)}
        />
      )}
    </div>
  )
}

export default QuizQuestionContent