import React, { useCallback, useEffect, useMemo, useState } from "react";
import {
  ClarityLevelSection,
  ModelComtainer,
  ModelContent,
  SelectedWord,
  SpeechAnalysisContent,
  SpeechAnalysisContentWordScore,
  SpeechAnalysisContentWordSection,
  SpeechAnalysisHeader,
  SpeechTitle,
} from "../style";
import HandIcon from "../icons/hand";
import classNames from "classnames";
import EarRight from "../icons/earRight";
import UserSpeak from "../icons/userSpeak";
import PenIcon from "../icons/pen";
import Mircophone from "../icons/mircophone";
import { Se, Tr } from "react-flags-select";
import Table from "./Table";
import TranslateDropdown from "./translateDropdown";
import { Progress } from "rsuite";
import ClarityItem from "./ClarityItem";
import InlineClampedText from "./InlineClampedText";
import PlayButton from "./PlayButton";
import useReportUtils from "../../hooks/useRreportUtils";
import useLanguages from "../api/useLanguage";
import useTranslation from "../../../../hooks/useTranslation.jsx";
import wordStore from "../../../../mc/wordStore.json";

const SpeechAnalysis = ({
  Aidata,
  isPersonal,
  setCheckingPlayingAudio,
  checkinhPlayingAudio,
}) => {
  const { findText } = useTranslation(wordStore);
  const [selectedWord, setSelectedWord] = useState(1);
  const [selectedSection, setSelectedSection] = useState(null);
  const [transalate, setTranslate] = useState(null);
  const { translateLangData, handleTranslate } = useLanguages();
  const { getColor, toRGBA } = useReportUtils();
  const wordData = Aidata?.words;
  const words = wordData?.map((item) => ({
    text: item?.wordText,
    value: item?.id,
    isCorrect: item?.isGood,
    color: item?.color,
  }));
  const selectedWordValue = wordData?.find((item) => item?.id === selectedWord);
  const sectionList = selectedWordValue?.optionData;
  const tabs = sectionList?.map((item) => {
    const tab = {
      label: item?.label,
      value: item?.id,
    };
    if (item?.id === "phoneme") {
      return {
        ...tab,
        icon: Mircophone,
      };
    }
    if (item?.id === "word_phoneme") {
      return {
        ...tab,
        icon: EarRight,
      };
    }
    if (item?.id === "clarity") {
      return {
        ...tab,
        icon: UserSpeak,
      };
    }
    if (item?.id === "standard_assessment") {
      return {
        ...tab,
        icon: PenIcon,
      };
    }
  });
  useEffect(() => {
    if (tabs?.length) {
      setSelectedSection(tabs?.[0]?.value);
    }
  }, [tabs?.length]);
  const selectionSelectionValue = sectionList?.find(
    (item) => item?.id === selectedSection,
  );
  const colors = useMemo(
    () => ({
      poor: "#F95454",
      excellent: "#30D468",
      fair: "#9747FF",
      // fair2: "#0D5FDB",
      good: "#0D7D96",
      veryGood: "#1A9243",
      pass: "#F39B33",
      okay: "#FEBF10",
    }),
    [],
  );
  const backgroundColors = useMemo(() => {
    const bg = {
      ...colors,
    };
    for (let x of Object.keys(bg)) {
      bg[x] = bg[x] + 10;
    }
    return bg;
  }, []);
  useEffect(() => {
    setTranslate(null);
  }, [selectedWord, selectionSelectionValue?.id]);
  const getFeekback = () => {
    const feedBack = [];
    if (selectionSelectionValue?.id === "phoneme") {
      selectionSelectionValue?.data?.forEach((item) => {
        feedBack?.unshift(item?.["Phoneme Feedback"]);
        feedBack?.unshift(item?.["Phoneme Feedback Summary"]);
      });
    }
    if (selectionSelectionValue?.id === "standard_assessment") {
      selectionSelectionValue?.testList?.map((item) => {
        feedBack?.unshift(item?.feedback);
      });
    }
    return feedBack;
  };
  const feedbackToTranslate = getFeekback();
  const findTranlatedWord = (label) => {
    if (!label) return "";
    const word = transalate?.find((item) => item?.text === label);
    return word?.value || label;
  };
  return (
    <ModelComtainer>
      <ModelContent>
        <SpeechAnalysisHeader>
          <SpeechTitle>
            <div className="label">
              <HandIcon />
              <p>{findText("Click on the words to see detailed feedback")}</p>
            </div>
            {isPersonal && (
              <div className="">
                <PlayButton
                  audio={Aidata?.audioData}
                  isStudent
                  notPlay={checkinhPlayingAudio.ai}
                  onPlaying={(value) => {
                    setCheckingPlayingAudio((prev) => ({
                      ...prev,
                      normal: value,
                    }));
                  }}
                />
                <PlayButton
                  type="ai"
                  refernceText={Aidata?.data?.Reference}
                  notPlay={checkinhPlayingAudio.normal}
                  onPlaying={(value) => {
                    setCheckingPlayingAudio((prev) => ({
                      ...prev,
                      ai: value,
                    }));
                  }}
                />
              </div>
            )}
          </SpeechTitle>

          <div className="transcript-wrapper">
            {words.map((word) => (
              <span>
                <span
                  key={word?.value}
                  style={{
                    color: word?.color,
                  }}
                  className={classNames({
                    selected: selectedWord === word?.value,
                    incorrect: !word?.isCorrect,
                    capitalise: word?.value === 1,
                  })}
                  onClick={() => setSelectedWord(word?.value)}
                >
                  {word.text}
                </span>
              </span>
            ))}
          </div>
          <ul className="no-border ul_tabs">
            {tabs?.map((tab) => (
              <li
                key={tab?.value}
                style={{
                  height: "40px",
                }}
                className={classNames({
                  active: selectedSection === tab?.value,
                })}
                onClick={() => setSelectedSection(tab?.value)}
              >
                <tab.icon
                  color={selectedSection === tab?.value ? "#f5f7f7" : "#949999"}
                />
                <p>{findText(tab?.label)}</p>
              </li>
            ))}
          </ul>
          <SelectedWord>
            {findText("Showing breakdown for:")}{" "}
            <span
              className="capitalise"
              style={{
                color: selectedWordValue?.color,
              }}
            >
              {selectedWordValue?.wordText}
            </span>
          </SelectedWord>
          <SpeechAnalysisContent>
            {selectionSelectionValue?.id === "phoneme" && (
              <Table>
                <div className="table_header">
                  <span>{findText("Phoneme")}</span>

                  <span>{findText("Score")}</span>

                  <span>{findText("Grade")}</span>
                  <div className="space-between">
                    <span>{findText("Feedback")}</span>
                    {isPersonal && (
                      <TranslateDropdown
                        loading={translateLangData?.loading}
                        key={selectedWordValue?.id}
                        onChange={async (lang) => {
                          const code = lang?.code;
                          if (code === "en" || !lang) {
                            setTranslate(null);
                            return;
                          }
                          const res = await handleTranslate({
                            texts: feedbackToTranslate,
                            source_language: "en",
                            target_language: code,
                          });
                          if (res?.data) {
                            const list = res?.data?.data?.map((item, idx) => {
                              const text = feedbackToTranslate[idx];
                              return {
                                text,
                                value: item?.translation,
                              };
                            });
                            setTranslate(list);
                          } else {
                            setTranslate(null);
                          }
                        }}
                      />
                    )}
                  </div>
                </div>
                <div className="table_row">
                  {selectionSelectionValue?.data?.map((item, idx) => {
                    const colorName = item.Grade.toLowerCase()?.replace(
                      / ([a-z])/gi,
                      (match, p1) => p1.toUpperCase(),
                    );
                    const isExcellent = item?.Grade === "Excellent";
                    const summary = findTranlatedWord(
                      item?.["Phoneme Feedback Summary"],
                    );
                    const des = findTranlatedWord(item?.["Phoneme Feedback"]);
                    return (
                      <div className="table_body" key={item?.id}>
                        <p>/{item?.Phoneme}/</p>
                        <p>{item?.Score || 0}%</p>

                        <p
                          className="status"
                          style={{
                            textTransform: "capitalize",
                            background: backgroundColors?.[colorName],
                            color: colors?.[colorName],
                          }}
                        >
                          {colorName === "veryGood" ? (
                            <span
                              style={{
                                textTransform: "none",
                              }}
                            >
                              {findText("Very good")}
                            </span>
                          ) : (
                            colorName
                          )}
                        </p>

                        {isExcellent ? (
                          item?.["Phoneme Feedback Summary"] &&
                          item?.["Phoneme Feedback"] ? (
                            <div className="feedback">
                              <div className="feedback_header">
                                <div className="feedback_header-content">
                                  {summary || ""}
                                </div>
                              </div>
                              <InlineClampedText
                                key={item?.id}
                                text={des || ""}
                              />
                            </div>
                          ) : (
                            <p className="good">
                              {findText(
                                "Perfect! you pronounced this sound correctly",
                              )}
                            </p>
                          )
                        ) : (
                          <div className="feedback">
                            <div className="feedback_header">
                              <div className="feedback_header-content">
                                {summary || ""}
                              </div>
                            </div>
                            <InlineClampedText
                              key={item?.id}
                              text={des || ""}
                            />
                          </div>
                        )}
                      </div>
                    );
                  })}
                </div>
              </Table>
            )}
            {selectionSelectionValue?.id === "word_phoneme" && (
              <SpeechAnalysisContentWordSection>
                <Table columns="1fr 1fr 1fr 1fr">
                  <div className="table_header">
                    <span>{findText("Syllables")}</span>

                    <span>{findText("Syllabic score")}</span>

                    <span>{findText("Syllable structure")}</span>
                    <span>{findText("Stress")}</span>
                  </div>
                  <div className="table_row">
                    {selectionSelectionValue?.data?.syllables?.map((item) => (
                      <div className="table_body" key={item?.id}>
                        <p className="lowercase">{`${item?.Onset} ${item?.Nucleus} ${item?.Coda}`}</p>
                        <p>{item?.["Syllabic Score"] || 0}%</p>
                        <p>
                          Onset{" "}
                          <span className="active lowercase">
                            ({item?.Onset})
                          </span>
                          , Nucleus{" "}
                          <span className="active lowercase">
                            ({item?.Nucleus})
                          </span>
                          , Coda{" "}
                          <span className="active lowercase">
                            ({item?.Coda})
                          </span>
                        </p>
                        <p>{item?.Stress}</p>
                      </div>
                    ))}
                  </div>
                </Table>
                <SpeechAnalysisContentWordScore>
                  <div className="progress_section center">
                    <div className="progress_value">
                      <Progress.Circle
                        percent={Math.floor(
                          selectionSelectionValue?.data?.score || 0,
                        )}
                        strokeWidth={10}
                        trailWidth={4}
                        strokeColor={getColor(
                          selectionSelectionValue?.data?.score || 0,
                        )}
                        trailColor={toRGBA(
                          getColor(selectionSelectionValue?.data?.score || 0),
                          0.1,
                        )}
                        showInfo={false}
                        className="progress-circle"
                        gapPosition={findText("bottom")}
                        style={{
                          width: "80px",
                        }}
                      />
                      <p
                        style={{
                          color: getColor(
                            selectionSelectionValue?.data?.score || 0,
                          ),
                        }}
                      >
                        {selectionSelectionValue?.data?.score || 0}%
                      </p>
                    </div>

                    <p className="label">{findText("Word score")}</p>
                  </div>
                  <div className="center">
                    <h4>
                      {selectionSelectionValue?.data?.syllable_count || 0}
                    </h4>
                    <p className="label">{findText("No. of syllables")}</p>
                  </div>
                </SpeechAnalysisContentWordScore>
              </SpeechAnalysisContentWordSection>
            )}
            {selectionSelectionValue?.id === "clarity" && (
              <ClarityLevelSection>
                <ClarityItem
                  title={findText("Speech rate")}
                  message={findText("Your average words spoken per minute.")}
                  value={findText("{speech_rate} (wpm)", {
                    speech_rate: `<span>${selectionSelectionValue?.data?.speech_rate}</span> <br/>`,
                  })}
                />
                <ClarityItem
                  title={findText("Fluency")}
                  message={findText(
                    "Your level of speaking proficiency in the language.",
                  )}
                  type="yellow"
                  value={`${selectionSelectionValue?.data?.fluency}%`}
                />
                <ClarityItem
                  title={findText("Audibility")}
                  message={findText(
                    "How clearly you project your voice while speaking.",
                  )}
                  type="purple"
                  value={findText("{audibility} (decibel level)", {
                    audibility: `<span>${selectionSelectionValue?.data?.audibility}</span><br/>`,
                  })}
                />
                <ClarityItem
                  title={findText("Intonation")}
                  message={findText(
                    "The rise and fall of your voice while speaking.",
                  )}
                  type="blue"
                  value={`${selectionSelectionValue?.data?.intonation}%`}
                />
                <ClarityItem
                  title={findText("What we heard")}
                  message={Aidata?.data?.Hypothesis}
                  type="pink"
                  alt
                />
                <ClarityItem
                  title={findText("Reference")}
                  message={Aidata?.data?.Reference}
                  type="blue"
                  alt
                />
              </ClarityLevelSection>
            )}
            {selectionSelectionValue?.id === "standard_assessment" && (
              <Table columns="1fr 1fr 60%">
                <div className="table_header">
                  <span>{findText("Test")}</span>

                  <span>{findText("Score")}</span>

                  <div className="space-between">
                    <span>{findText("Feedback:")}</span>
                    {isPersonal && (
                      <TranslateDropdown
                        loading={translateLangData?.loading}
                        onChange={async (lang) => {
                          const code = lang?.code;
                          if (code === "en" || !lang) {
                            setTranslate(null);
                            return;
                          }
                          const res = await handleTranslate({
                            texts: feedbackToTranslate,
                            source_language: "en",
                            target_language: code,
                          });
                          if (res?.data) {
                            const list = res?.data?.data?.map((item, idx) => {
                              const text = feedbackToTranslate[idx];
                              return {
                                text,
                                value: item?.translation,
                              };
                            });
                            setTranslate(list);

                            console.log(res?.data);
                          } else {
                            setTranslate(null);
                          }
                        }}
                      />
                    )}
                  </div>
                </div>
                <div className="table_row">
                  {selectionSelectionValue?.testList?.map((item) => {
                    const feedback = transalate
                      ? findTranlatedWord(item?.feedback)
                      : item?.feedback;
                    return (
                      <div className="table_body" key={item?.title}>
                        <p
                          className="active semi-bold"
                          style={{
                            color: item?.color,
                          }}
                        >
                          {item?.title}
                        </p>
                        <p>
                          {item?.total
                            ? findText("{score} of {total}", {
                                score: item?.score,
                                total: item?.total,
                              })
                            : item?.score}
                        </p>
                        <p>
                          <InlineClampedText
                            key={item?.title}
                            text={feedback || ""}
                          />
                        </p>
                      </div>
                    );
                  })}
                </div>
              </Table>
            )}
          </SpeechAnalysisContent>
        </SpeechAnalysisHeader>
      </ModelContent>
    </ModelComtainer>
  );
};
export default SpeechAnalysis;
