import React, { useState } from 'react';
import { Phases } from '../../../model/common';
import { RingProps } from '../../../model/components/ring';
import updatePhaseAndScore from '../../../utils/updatePhaseAndScore';
import RoundedButton from '../../common/RoundedButton';
import ChallengeIcon from '../../icons/Challenge';
import EndOfPhase from './EndOfPhase';
import PhaseHeader from './PhaseHeader';
import QuestionItem from './QuestionItem';

const Challenge: React.FC<RingProps> = ({ ring, user }) => {
  const {
    challenge: {
      question,
      info: { value },
    },
  } = ring;

  const [selected, setSelected] = useState<string>();
  const [showFeedback, setShowFeedback] = useState<boolean>(false);
  const [score, setScore] = useState<number>(0);

  const onEnd = async (): Promise<void> => {
    const response = await updatePhaseAndScore(
      user,
      3,
      ring.id,
      value / user.team.members,
      {
        challengeAnswer: {
          number: 1,
          answer: question.answers.find((ans) => ans.id === selected).text,
        },
      },
    );
    setScore(response.data.team.totalScore);
    setShowFeedback(true);
  };

  return (
    <>
      {showFeedback && (
        <EndOfPhase
          ring={ring}
          points={value}
          phase={Phases.Three}
          teamMembers={user.team?.members}
          totalScore={score}
        />
      )}
      <section className="challenge">
        <PhaseHeader ring={ring} icon={<ChallengeIcon />} phase="Reto" />
        <form>
          <fieldset>
            <div className="questionsWrapper">
              <div className="questionsPosition">
                <QuestionItem
                  key={question.id}
                  title={question.question}
                  image={question.picture}
                  points={value}
                >
                  <p>{question.description}</p>
                  <div className="optionsGrid">
                    {question.answers.map((i) => (
                      <button
                        key={i.id}
                        type="button"
                        onClick={(): void => setSelected(i.id)}
                        className={`challengeOption${
                          i.id === selected ? ' selected' : ''
                        }`}
                      >
                        <p className="text">{i.text}</p>
                      </button>
                    ))}
                  </div>
                </QuestionItem>
              </div>
            </div>
            <div className="controls">
              <RoundedButton
                type="button"
                title="Enviar"
                size="small"
                onClick={onEnd}
                isDisabled={!selected}
              />
            </div>
          </fieldset>
        </form>
      </section>
    </>
  );
};

export default Challenge;
