import React, { useContext, useEffect, useState } from "react";
import constants from "./contants";
import ArrowLeft from "../../../assets/svg/arrowLeft";
import YellowPen from "../../../assets/svg/yellow-pen";
import {
  Container,
  Content,
  Header,
  ScoreBadge,
  ScoreHeader,
  ScoreRight,
  QuestionContent,
  QuestionTitle,
  ScoreHeaderContainer,
  QuestionNav,
  QuestionWrapper,
  Loader,
  // QuestionFooter,
} from "./style";
import Comment from "./components/comment";
// import ButtonComponent from "../../button";
import EssayWritten from "./questions/essayWritten";
import EssayScripted from "./questions/essayScripted";
import EssayUnscripted from "./questions/essayUnscripted";
import SoundPlay from "./questions/soundPlay";
import Reading from "./questions/reading";
import WordPlayText from "./questions/wordPlayText";
import WordPlayMultipleChoice from "./questions/wordPlayMultipleChoice";
import MatchPair from "./questions/matchPair";
import QuizQuestion from "./components/quizQuestion";
import QuizScripted from "./questions/quizScripted";
import QuizUnscripted from "./questions/quizUnsripted";
import QuizMultipleChoice from "./questions/quizMultipleChoice";
import DialogueScripted from "./questions/dialogueScripted";
import DialogueUnscripted from "./questions/dialogueUnscripted";
import GradingModal from "./components/modals/gradingModal";
import classNames from "classnames";
import FullAnalysis from "../fullAnalysis";
import useApi from "./api";
import FullPageLoader from "../../fullPageLoader";
import { ButtonComponent, OutletContext } from "../..";
import useReportUtils from "../hooks/useRreportUtils";
import InfoIcon2 from "../fullAnalysis/icons/info";
import { NavBack, NavForword } from "../fullAnalysis/icons/navArrow";
import useTranslation from "../../../hooks/useTranslation.jsx";
import wordStore from "../../../mc/wordStore.json";
import QuizNewWritten from "./questions/quizNewWritten.jsx";

const ReportQuestions = ({
  accountType,
  AiData,
  onClose,
  testId,
  questions = [],
  questionData,
  questionActivityID,
  answerData,
  onSwitchQuestion,
  loading,
  mainTitle,
  analysisLoading = false,
  onScoreSaved,
  navControl = {
    on: false,
    disablePrev: false,
    disableNext: false,
    onNext: () => {},
    onPrev: () => {},
  },
}) => {
  const { findText } = useTranslation(wordStore);
  const [questionList, setQuestionList] = useState([]);
  const [defaultSelected, setDefaultSelected] = useState(1);
  useEffect(() => {
    if (questions?.length) {
      setQuestionList(questions);
    }
  }, [questions]);
  const findedQuestion = questionData || {};
  const { getQuestionInfo } = useReportUtils();
  const questionType = getQuestionInfo(findedQuestion)?.type;
  const [comment, setComment] = useState(null);
  const [intructorScore, setInstructorScore] = useState(0);
  const [AIScore, setAIScore] = useState(0);
  const [toggleGrade, setToggleGrade] = useState(false);
  const [toggle, setToggle] = useState(null);
  const { affiliateAccount } = useContext(OutletContext);
  const enterpriseId = affiliateAccount?.id;
  const { formatNumber } = useReportUtils();
  const { handleGradeQuestion, gradeQuestionData } = useApi();
  const question = constants.questions.find(
    (question) => question.value === questionType,
  );
  const commentData = answerData?.answer?.comments;
  const hasAnswer = answerData?.answer?.data;
  useEffect(() => {
    if (commentData?.length && findedQuestion?.question_id)
      setComment(commentData?.[0]);
    else {
      setComment(null);
    }
  }, [commentData, findedQuestion?.question_id, questionActivityID]);
  useEffect(() => {
    if (findedQuestion?.question_id) {
      if (
        accountType === "instructor-personal" ||
        accountType === "instructor-affiliate"
      )
        setInstructorScore(answerData?.grading_data?.score || 0);
      else setInstructorScore(answerData?.score || 0);

      setAIScore(answerData?.ai_score || 0);
    }
  }, [findedQuestion?.question_id, questionActivityID, answerData]);

  const handleScore = async (value) => {
    if (!questionActivityID || !enterpriseId || !answerData?.answer?.session_id)
      return;
    const res = await handleGradeQuestion(
      questionActivityID,
      answerData?.answer?.session_id,
      value,
      enterpriseId,
    );
    if (res?.data || (res?.status >= 200 && res?.status < 300)) {
      setInstructorScore(value?.score);
      setToggleGrade(false);
      onScoreSaved?.(res);
    }
  };
  if (toggle) {
    return (
      <FullAnalysis
        accountType={accountType}
        modelData={toggle}
        modelsTypes={question.model_type}
        onClose={() => {
          setDefaultSelected(toggle?.defaultSelected || 1);
          setToggle(null);
        }}
      />
    );
  }
  const showAIScore = question?.ai_score_available;
  const noAi = question?.system_score;

  /// navigating question
  const currentQuestionIndex = questions.findIndex(
    (q) => q?.question_activity_id === questionActivityID,
  );
  const prevId = questions?.[currentQuestionIndex - 1]?.question_activity_id;
  const nextId = questions?.[currentQuestionIndex + 1]?.question_activity_id;

  const reset = () => {
    setAIScore(0);
    setInstructorScore(0);
    setComment(null);
    setDefaultSelected(1);
  };
  const handleNext = () => {
    reset();

    if (nextId) onSwitchQuestion?.(nextId);
  };
  const handlePrev = () => {
    reset();
    if (prevId) onSwitchQuestion?.(prevId);
  };

  const isPersonal = accountType === "personal";
  return (
    <Container>
      {(gradeQuestionData?.loading || loading) && (
        <FullPageLoader fixed hasBackground />
      )}
      {toggleGrade && (
        <GradingModal
          key={questionActivityID}
          aiValue={formatNumber(AIScore || 0)}
          suggestionValue={formatNumber(findedQuestion?.suggested_score || 0)}
          noAi={noAi}
          setScore={handleScore}
          defaultScore={formatNumber(intructorScore || 0)}
          showAIScore={showAIScore}
          onClose={() => {
            setToggleGrade(false);
          }}
        />
      )}
      <Header onClick={onClose}>
        <ArrowLeft />
        {question && !loading && (
          <h1>
            {mainTitle || question?.label}

            {/* {question.type && <span>({question.type})</span>} */}
          </h1>
        )}
      </Header>
      <Content>
        <ScoreHeaderContainer>
          <ScoreHeader>
            {showAIScore &&
              accountType !== "personal" &&
              typeof AIScore === "number" && (
                <ScoreBadge ai>
                  {findText("AI score:")}{" "}
                  <span>{loading ? "--" : formatNumber(AIScore) + "%"}</span>
                </ScoreBadge>
              )}
            {noAi &&
              accountType !== "personal" &&
              typeof findedQuestion?.suggested_score === "number" && (
                <ScoreBadge ai>
                  {findText("Score:")}{" "}
                  <span>
                    {loading
                      ? "--"
                      : formatNumber(findedQuestion?.suggested_score || 0) +
                        "%"}
                  </span>
                </ScoreBadge>
              )}

            <ScoreBadge>
              {findText("Instructor’s score:")}{" "}
              <span>
                {loading || typeof intructorScore !== "number"
                  ? "--"
                  : formatNumber(intructorScore) + "%"}
              </span>
            </ScoreBadge>

            {(accountType === "instructor-personal" ||
              accountType === "instructor-affiliate") && (
              <button
                disabled={(!hasAnswer && findedQuestion) || loading}
                onClick={() => {
                  setToggleGrade(true);
                }}
              >
                <YellowPen color={findText("#fff")} />
              </button>
            )}

            <InfoIcon2 />
          </ScoreHeader>
          <QuestionNav>
            {navControl?.on ? (
              <>
                <button
                  disabled={navControl.disablePrev}
                  onClick={navControl.onPrev}
                >
                  <NavBack disabled={navControl.disablePrev} />
                  {findText("Previous question")}
                </button>
                <button
                  disabled={navControl.disableNext}
                  onClick={navControl.onNext}
                >
                  {findText("Next question")}
                  <NavForword disabled={navControl.disableNext} />
                </button>
              </>
            ) : (
              <>
                <button disabled={!prevId} onClick={handlePrev}>
                  <NavBack disabled={!prevId} />
                  {findText("Previous question")}
                </button>
                <button disabled={!nextId} onClick={handleNext}>
                  {findText("Next question")}
                  <NavForword disabled={!nextId} />
                </button>
              </>
            )}
          </QuestionNav>
        </ScoreHeaderContainer>
        {/* {data && !hasAnswer && <ErrorHeader />} */}

        {loading ? (
          <Loader></Loader>
        ) : (
          <QuestionWrapper>
            <QuestionContent>
              {findedQuestion && (
                <>
                  {questionType === "essay-written" && (
                    <EssayWritten
                      data={findedQuestion}
                      answerData={answerData}
                      aiData={AiData}
                      setToggle={setToggle}
                      isPersonal={isPersonal}
                      analysisLoading={analysisLoading}
                      key={analysisLoading}
                    />
                  )}
                  {questionType === "essay-scripted" && (
                    <EssayScripted
                      data={findedQuestion}
                      answerData={answerData}
                      aiData={AiData}
                      setToggle={setToggle}
                      isPersonal={isPersonal}
                      analysisLoading={analysisLoading}
                      key={analysisLoading}
                    />
                  )}
                  {questionType === "essay-unscripted" && (
                    <EssayUnscripted
                      data={findedQuestion}
                      answerData={answerData}
                      aiData={AiData}
                      setToggle={setToggle}
                      isPersonal={isPersonal}
                      analysisLoading={analysisLoading}
                      key={analysisLoading}
                    />
                  )}
                  {questionType === "sound-play" && (
                    <SoundPlay
                      data={findedQuestion}
                      answerData={answerData}
                      aiData={AiData}
                      setToggle={setToggle}
                      isPersonal={isPersonal}
                      analysisLoading={analysisLoading}
                      key={analysisLoading}
                    />
                  )}
                  {questionType === "reading" && (
                    <Reading
                      data={findedQuestion}
                      answerData={answerData}
                      aiData={AiData}
                      setToggle={setToggle}
                      isPersonal={isPersonal}
                      analysisLoading={analysisLoading}
                      key={analysisLoading}
                    />
                  )}
                  {questionType === "word-play-text" && (
                    <WordPlayText
                      data={findedQuestion}
                      answerData={answerData}
                      isPersonal={isPersonal}
                    />
                  )}
                  {questionType === "word-play-multiple-choice" && (
                    <WordPlayMultipleChoice
                      data={findedQuestion}
                      answerData={answerData}
                      isPersonal={isPersonal}
                    />
                  )}
                  {questionType === "match-pair" && (
                    <MatchPair
                      data={findedQuestion}
                      answerData={answerData}
                      isPersonal={isPersonal}
                    />
                  )}
                  {questionType === "quiz-scripted" && (
                    <QuizScripted
                      data={findedQuestion}
                      answerData={answerData}
                      aiData={AiData}
                      setToggle={setToggle}
                      isPersonal={isPersonal}
                      defaultSelected={defaultSelected}
                      analysisLoading={analysisLoading}
                      key={analysisLoading}
                    />
                  )}
                  {questionType === "quiz-unscripted" && (
                    <QuizUnscripted
                      data={findedQuestion}
                      answerData={answerData}
                      aiData={AiData}
                      setToggle={setToggle}
                      isPersonal={isPersonal}
                      defaultSelected={defaultSelected}
                      analysisLoading={analysisLoading}
                      key={analysisLoading}
                    />
                  )}
                  {questionType === "quiz-written" && (
                    <QuizNewWritten
                      data={findedQuestion}
                      answerData={answerData}
                      aiData={AiData}
                      setToggle={setToggle}
                      isPersonal={isPersonal}
                      defaultSelected={defaultSelected}
                      analysisLoading={analysisLoading}
                      key={analysisLoading}
                    />
                  )}
                  {questionType === "quiz-multiple-choice" && (
                    <QuizMultipleChoice
                      data={findedQuestion}
                      answerData={answerData}
                      isPersonal={isPersonal}
                    />
                  )}

                  {questionType === "dialogue-scripted" && (
                    <DialogueScripted
                      data={findedQuestion}
                      answerData={answerData}
                      aiData={AiData}
                      setToggle={setToggle}
                      isPersonal={isPersonal}
                      defaultSelected={defaultSelected}
                      analysisLoading={analysisLoading}
                      key={analysisLoading}
                    />
                  )}

                  {questionType === "dialogue-unscripted" && (
                    <DialogueUnscripted
                      data={findedQuestion}
                      answerData={answerData}
                      aiData={AiData}
                      setToggle={setToggle}
                      isPersonal={isPersonal}
                      defaultSelected={defaultSelected}
                      analysisLoading={analysisLoading}
                      key={analysisLoading}
                    />
                  )}
                </>
              )}
            </QuestionContent>

            <Comment
              data={comment}
              key={comment?.created_at}
              testId={testId}
              setData={setComment}
              disabledAdd={!hasAnswer}
              questionActivityID={questionActivityID}
              editMode={
                accountType === "instructor-personal" ||
                accountType === "instructor-affiliate"
              }
            />
          </QuestionWrapper>
        )}
        {/* {(accountType === "instructor-personal" ||
          accountType === "instructor-affiliate") && (
          <QuestionFooter>
            <ButtonComponent text="Save" onClick={onClose} />
          </QuestionFooter>
         )} */}
      </Content>
    </Container>
  );
};
export default ReportQuestions;
