import { createContext, useContext, useEffect, useState } from "react";
import { OutletContext } from "../../AppMainLayout";
import {
  Container,
  Content,
  EmptyModel,
  EmptyModelDesc,
  MainSection,
  // ProgressCircleSection,
  ProgressSidebar,
  Sidebar,
  SpeechSideSection,
} from "./style";
import { Header } from "../reportQuestions/style";
import ArrowLeft from "../../../assets/svg/arrowLeft";
import { Progress } from "rsuite";
import PlayButton from "./components/PlayButton";
import Tabs from "../reportQuestions/components/tabs";
import Evaluation from "./components/Evaluation";
import SpeechAnalysis from "./components/SpeechAnalysis";
import Grammar from "./components/Grammar";
import classNames from "classnames";
import WarningGrey from "../../../assets/svg/warningGrey";
import useLanguages from "./api/useLanguage";
import useReportUtils from "../hooks/useRreportUtils";
import GrammarV2 from "./components/Grammar.v2";
import useTranslation from "../../../hooks/useTranslation.jsx";
import wordStore from "../../../mc/wordStore.json";
import Comprehension from "./components/Comprehension.jsx";
import EmptyBoxIcon from "./icons/emptyBoxIcon.jsx";
const FullAnalysis = ({
  onClose,
  accountType,
  modelsTypes = [],
  modelData,
}) => {
  const { getColor, toRGBA, validateModels } = useReportUtils();
  const data = validateModels(modelData, modelsTypes);
  const { findText } = useTranslation(wordStore);
  const { setRightLayout, setCenterLayoutStyle } = useContext(OutletContext);
  const [checkinhPlayingAudio, setCheckingPlayingAudio] = useState({
    ai: false,
    normal: false,
  });
  const tabs = data?.models?.map((item) => ({
    label: findText(item?.label),
    value: item?.id,
  }));
  const [selected, setSelected] = useState(tabs?.[0]?.value || "");
  useEffect(() => {
    if (tabs?.length) {
      setSelected(tabs[0].value);
    }
  }, [tabs?.length]);
  useEffect(() => {
    setRightLayout(null);
    setCenterLayoutStyle({
      marginRight: 0,
    });
    return () => {
      setRightLayout(true);
      setCenterLayoutStyle({
        marginRight: "252px",
      });
    };
  }, []);
  const sideModels =
    data &&
    data?.models?.slice().sort((a, b) => {
      return (
        (b?.sideProgress === true ? 1 : 0) - (a?.sideProgress === true ? 1 : 0)
      );
    });

  // const firstModel = sideModels && sideModels?.[0];
  // const secondModel = sideModels && sideModels?.[1];
  // const thirdModel = sideModels && sideModels?.[2];

  const selectedModel =
    data && data?.models?.find((item) => item?.id === selected);
  const handleClose = () => {
    setRightLayout(true);
    setCenterLayoutStyle({
      marginRight: "252px",
    });
    onClose?.();
  };
  const { handleGetLanguages, languageData } = useLanguages();
  useEffect(() => {
    handleGetLanguages();
  }, []);
  return (
    <FullAnalysisContext.Provider
      value={{
        languageData,
      }}
    >
      <Container>
        <Header onClick={handleClose}>
          <ArrowLeft />
          <h1>{findText("Full analysis")}</h1>
        </Header>
        <Content
          className={classNames({
            personal: accountType === "personal",
          })}
        >
          {accountType !== "personal" && (
            <Sidebar>
              <ProgressSidebar>
                {/* <ProgressCircleSection>
                 {thirdModel && (
                  <Progress.Circle
                    percent={thirdModel?.score}
                    strokeWidth={4}
                    trailWidth={4}
                    strokeColor={thirdModel?.primaryColor}
                    trailColor="#F2F2F2"
                    showInfo={false}
                    className="progress-circle"
                    style={{
                      width: "130px",
                    }}
                  />
                 )}
                 {secondModel && (
                  <Progress.Circle
                    percent={secondModel?.score}
                    strokeWidth={4}
                    trailWidth={4}
                    strokeColor={secondModel?.primaryColor}
                    trailColor="#F2F2F2"
                    showInfo={false}
                    className="progress-circle"
                    style={{
                      width: "110px",
                    }}
                  />
                 )}
                 {firstModel && (
                  <Progress.Circle
                    percent={firstModel?.score}
                    strokeWidth={4}
                    trailWidth={4}
                    strokeColor={firstModel?.primaryColor}
                    trailColor={"#F2F2F2"}
                    showInfo={false}
                    className="progress-circle"
                    style={{
                      width: "90px",
                    }}
                  />
                 )}
                 <p>
                  AI score <br />
                  <span>{data?.AiScore || 0}%</span>
                 </p>
                 </ProgressCircleSection> */}
                <ul>
                  {sideModels?.map((model) => {
                    const color = getColor(
                      parseInt(Math.floor(model?.score) || 0)
                    );
                    const bgColor = toRGBA(color, 0.1);
                    return (
                      <li key={model?.id}>
                        {model?.id === "logic_evaluation" ? (
                          <p>{findText(`Logic evaluation point`)}</p>
                        ) : model?.id === "speech_analysis" ? (
                          <p>{findText(`Speech analysis point`)}</p>
                        ) : model?.id === "grammar" ? (
                          <p>{findText(`Grammar point`)}</p>
                        ) : (
                          <p>{findText(`Comprehension point`)}</p>
                        )}

                        {model?.sideProgress ? (
                          <div
                            style={{
                              backgroundColor: bgColor,
                            }}
                            className="progress-section"
                          >
                            <span
                              style={{
                                color,
                              }}
                            >
                              {Math.floor(model?.score) || 0}%
                            </span>
                            <Progress.Line
                              percent={model?.score || 0}
                              strokeWidth={8}
                              trailWidth={8}
                              strokeColor={color}
                              trailColor={"#fff"}
                              showInfo={false}
                              style={{
                                width: "100%",
                              }}
                            />
                          </div>
                        ) : (
                          <div className="no-score">
                            <WarningGrey color="#FEBF10" />
                            <p>
                              {findText(
                                "Note: This is currently not assigned a point value."
                              )}
                            </p>
                          </div>
                        )}
                      </li>
                    );
                  })}
                </ul>
              </ProgressSidebar>
              {selectedModel?.id === "speech_analysis" &&
                !selectedModel?.isEmpty && (
                  <SpeechSideSection>
                    <PlayButton
                      audio={selectedModel?.audioData}
                      notPlay={checkinhPlayingAudio.ai}
                      onPlaying={(value) => {
                        setCheckingPlayingAudio((prev) => ({
                          ...prev,
                          normal: value,
                        }));
                      }}
                    />
                    <PlayButton
                      type="ai"
                      refernceText={selectedModel?.data?.Reference}
                      notPlay={checkinhPlayingAudio.normal}
                      onPlaying={(value) => {
                        setCheckingPlayingAudio((prev) => ({
                          ...prev,
                          ai: value,
                        }));
                      }}
                    />
                  </SpeechSideSection>
                )}
            </Sidebar>
          )}
          <MainSection>
            {tabs?.length > 0 && (
              <Tabs options={tabs} selected={selected} onChange={setSelected} />
            )}

            {selectedModel?.isEmpty ? (
              <EmptyModel>
                <EmptyModelDesc>
                  <EmptyBoxIcon />
                  <h2>{findText("Analysis unavailable")}</h2>
                  <p>{findText("We couldn’t generate it this time.")}</p>
                </EmptyModelDesc>
              </EmptyModel>
            ) : (
              <>
                {selectedModel?.id === "logic_evaluation" && (
                  <Evaluation
                    Aidata={selectedModel}
                    isPersonal={accountType === "personal"}
                  />
                )}
                {selectedModel?.id === "speech_analysis" && (
                  <SpeechAnalysis
                    Aidata={selectedModel}
                    isPersonal={accountType === "personal"}
                    checkinhPlayingAudio={checkinhPlayingAudio}
                    setCheckingPlayingAudio={setCheckingPlayingAudio}
                  />
                )}
                {selectedModel?.id === "comprehension" && (
                  <Comprehension
                    Aidata={selectedModel}
                    isPersonal={accountType === "personal"}
                  />
                )}
                {selectedModel?.id === "grammar" && (
                  <>
                    {selectedModel?.version === 2 ? (
                      <GrammarV2
                        Aidata={selectedModel}
                        isPersonal={accountType === "personal"}
                      />
                    ) : (
                      <Grammar Aidata={selectedModel} />
                    )}
                  </>
                )}
              </>
            )}
          </MainSection>
        </Content>
      </Container>
    </FullAnalysisContext.Provider>
  );
};
export const FullAnalysisContext = createContext(null);
export default FullAnalysis;
