import React, { useState } from 'react';
import ArrowRight from '../../icons/ArrowRight';
import IconButton from '../../common/IconButton';
import ArrowLeft from '../../icons/ArrowLeft';
import PhaseHeader from './PhaseHeader';
import RoundedButton from '../../common/RoundedButton';
import QuestionItem from './QuestionItem';
import CloseBig from '../../icons/CloseBig';
import CheckBig from '../../icons/CheckBig';
import { RingProps } from '../../../model/components/ring';
import EndOfPhase from './EndOfPhase';
import { Phases } from '../../../model/common';
import getTrivialIcon from '../../../utils/getTrivialIcon';
import checkTrivialAnswers from '../../../utils/checkTrivialAnswers';
import updatePhaseAndScore from '../../../utils/updatePhaseAndScore';
import mapTrivialAnswers from '../../../utils/mapTrivialAnswers';

const Trivial: React.FC<RingProps> = ({ ring, user }) => {
  const { trivial, id } = ring;

  const {
    questions,
    info: { value },
  } = trivial;

  const [answerState, setAnswerState] = useState<Map<string, string>>(
    new Map<string, string>(),
  );

  const [currentQuestion, setQuestion] = useState<number>(0);
  const [showAnswers, setShowAnswers] = useState<boolean>(false);
  const [showEndOfPhase, setShowEnd] = useState<boolean>(false);
  const [score, setScore] = useState<number>(0);

  const onSubmit = async (): Promise<void> => {
    if (!showAnswers) {
      const answerData = mapTrivialAnswers(trivial, answerState);
      const points = checkTrivialAnswers(trivial, answerState);
      const response = await updatePhaseAndScore(
        user,
        2,
        id,
        points / user.team.members,
        {
          testAnswers: answerData,
        },
      );
      setScore(response.data.team.totalScore);
      setShowAnswers(true);
    } else {
      setShowEnd(true);
    }
  };

  const onOptionClick = (question: string, answer: string): void => {
    setAnswerState(new Map(answerState.set(question, answer)));
  };

  return (
    <>
      {showEndOfPhase && (
        <EndOfPhase
          ring={ring}
          phase={Phases.Two}
          points={checkTrivialAnswers(trivial, answerState)}
          teamMembers={user.team?.members}
          totalScore={score}
        />
      )}
      <section className="trivial">
        <PhaseHeader
          ring={ring}
          icon={getTrivialIcon(answerState.size)}
          phase="Trivial"
        />
        <form>
          <fieldset>
            <div className="questionsWrapper">
              <div
                className="questionsPosition"
                style={{
                  width: `calc(${questions.length} * 100vw)`,
                  transform: `translateX(calc(${currentQuestion} * -100vw))`,
                }}
              >
                {questions.map((item, index) => {
                  return (
                    <QuestionItem
                      key={item.id}
                      title={item.question}
                      number={index + 1}
                      image={item.picture}
                      points={value / questions.length}
                    >
                      {item.answers.map((i, answerIndex) => {
                        const isSelected = answerState.get(item.id) === i.id;
                        return (
                          <button
                            key={i.id}
                            disabled={showAnswers}
                            onClick={(): void => onOptionClick(item.id, i.id)}
                            type="button"
                            className={`trivialOption${
                              isSelected ? ' selected' : ''
                            }${
                              showAnswers && i.isCorrect && !isSelected
                                ? ' validated'
                                : ''
                            }`}
                          >
                            <p className="letter">
                              {['A', 'B', 'C', 'D'][answerIndex]}
                            </p>
                            <p className="text">{i.text}</p>
                            {showAnswers && (isSelected || i.isCorrect) ? (
                              <div className="validation">
                                {!i.isCorrect ? (
                                  <CloseBig size="medium" />
                                ) : (
                                  <CheckBig />
                                )}
                              </div>
                            ) : null}
                          </button>
                        );
                      })}
                      <p className="instructions">
                        Haz click en la opción correcta
                      </p>
                    </QuestionItem>
                  );
                })}
              </div>
            </div>
            <div className="controls">
              <IconButton
                title="Anterior"
                size="small"
                isDisabled={currentQuestion === 0}
                onClick={(): void => setQuestion(currentQuestion - 1)}
              >
                <ArrowLeft />
              </IconButton>
              <RoundedButton
                type="button"
                onClick={onSubmit}
                title={showAnswers ? 'Finalizar' : 'Comprobar'}
                size="small"
                isDisabled={answerState.size !== questions.length}
              />
              <IconButton
                title="Siguiente"
                size="small"
                isDisabled={currentQuestion === questions.length - 1}
                onClick={(): void => setQuestion(currentQuestion + 1)}
              >
                <ArrowRight />
              </IconButton>
            </div>
          </fieldset>
        </form>
      </section>
    </>
  );
};
export default Trivial;
