import React, { useEffect, useState } from "react";
import {
  QuestionSection,
  QuestionSectionAction,
  QuestionSectionWithAnalysis,
} from "../style";
import Tabs from "../components/tabs";
import useReportUtils from "../../hooks/useRreportUtils";
import Response from "../components/response";
import QuestionDropdown from "../components/questionDropdown";
import AnalysisButton from "../components/analysisButton";
import QuizQuestion from "../components/quizQuestion";
import wordStore from "../../../../mc/wordStore.json";
import useTranslation from "../../../../hooks/useTranslation.jsx";

const QuizNewWritten = ({
  data,
  aiData,
  answerData,
  isPersonal,
  defaultSelected = 1,
  setToggle,
  analysisLoading,
}) => {
  const { findText } = useTranslation(wordStore);
  const [selected, setSelected] = useState(defaultSelected);
  const { quizResponses, setupAnalysis, quizWrittenSelectedModel } =
    useReportUtils();

  const [analysis, setAnalysis] = useState(null);
  const quizList = quizResponses({
    responses: answerData?.answer?.data?.data?.responses,
    type: "written",
  });
  const selectionList = quizList?.map((item) => ({
    value: item?.key,
    label: findText(`Reponses {arg1}`, { arg1: item?.key }),
  }));
  const selectedResponse =
    quizList?.find((item) => item?.key === selected) || {};

  const selectedModel = quizWrittenSelectedModel(selectedResponse, aiData);

  useEffect(() => {
    if (selectedResponse) {
      const models = setupAnalysis(selectedModel, null, data?.ai_score);
      setAnalysis(models);
    }
  }, [selectedResponse?.key]);
  return (
    <>
      <QuestionSection>
        <Tabs
          options={selectionList}
          selected={selected}
          onChange={setSelected}
        />

        <QuestionDropdown>
          <>
            <li>
              <h3>{findText("Instruction")}</h3>
              <p>{data?.question_data?.instruction}</p>
            </li>
            <li>
              <QuizQuestion data={data} />
            </li>
            <li>
              <h3>{findText("Question")}</h3>
              <p>{data?.question_data?.question_data?.question}</p>
            </li>
          </>
        </QuestionDropdown>
        <Response response={selectedResponse?.text} isPersonal={isPersonal} />

        <QuestionSectionWithAnalysis>
          <QuestionSectionAction>
            <AnalysisButton
              loading={analysisLoading}
              disabled={!(analysis?.models?.length > 0) || analysisLoading}
              onClick={() => {
                setToggle({
                  ...analysis,
                  defaultSelected: selected,
                });
              }}
            />
          </QuestionSectionAction>
        </QuestionSectionWithAnalysis>
      </QuestionSection>
    </>
  );
};

export default QuizNewWritten;
