import Loader from 'components/Loader/Loader'
import { useClient } from 'cozy-client'
import { QuestionEntity, UserChallenge } from 'models'
import React, { useEffect, useRef, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import QuizService from 'services/quiz.service'
import { useAppSelector } from 'store/hooks'
import './quizQuestion.scss'
import QuizQuestionContent from './QuizQuestionContent'
import QuizQuestionContentCustom from './QuizQuestionContentCustom'

const QuizQuestion = ({ userChallenge }: { userChallenge: UserChallenge }) => {
  const client = useClient()
  const navigate = useNavigate()
  const { fluidTypes } = useAppSelector(state => state.ecolyo.global)

  const questionsIsLocked = userChallenge.quiz.questions.some(
    answer => answer.result == 0
  )
  const [customQuestion, setCustomQuestion] = useState<QuestionEntity>()
  const [isCustomQuest, setIsCustomQuest] = useState(!questionsIsLocked)

  const mainContentRef = useRef<HTMLDivElement>(null)
  const focusMainContent = () => {
    setTimeout(() => mainContentRef.current?.focus(), 0)
  }

  const goBack = () => {
    navigate('/challenges')
  }

  useEffect(() => {
    let subscribed = true
    async function loadCustomQuestion() {
      const quizService = new QuizService(client)
      const customQuestion = await quizService.getCustomQuestion(
        userChallenge.quiz.customQuestion,
        fluidTypes
      )
      setCustomQuestion(customQuestion)
    }
    if (isCustomQuest && subscribed) {
      loadCustomQuestion()
    }
    return () => {
      subscribed = false
    }
  }, [client, fluidTypes, isCustomQuest, userChallenge.quiz.customQuestion])

  if (isCustomQuest && !customQuestion) {
    return (
      <div ref={mainContentRef} className="quiz-content" tabIndex={-1}>
        <div className="question-loading">
          <Loader />
        </div>
      </div>
    )
  }

  if (isCustomQuest && customQuestion) {
    return (
      <div ref={mainContentRef} className="quiz-content" tabIndex={-1}>
        <QuizQuestionContentCustom
          userChallenge={userChallenge}
          goBack={goBack}
          customQuestion={customQuestion}
        />
      </div>
    )
  }

  return (
    <div ref={mainContentRef} className="quiz-content" tabIndex={-1}>
      <QuizQuestionContent
        userChallenge={userChallenge}
        setIsCustomQuest={setIsCustomQuest}
        goBack={goBack}
        focusCallback={focusMainContent}
      />
    </div>
  )
}

export default QuizQuestion