import React, { useCallback, useEffect } from "react";
import {
  GrammarContent,
  GrammarHeader,
  GrammarHeaderContent,
  GrammarV2Content,
  GrammarV2ContentWrapper,
  GrammarV2ContentWrapperTranslate,
  GrammarV2Correct,
  GrammarV2Feedback,
  GrammarV2FeedbackList,
  GrammarV2HeaderContent,
  GrammarV2HeaderContentWrapper,
  ModelComtainer,
  ModelContent,
} from "../style";
import HandIcon from "../icons/hand";
import classNames from "classnames";
import ChatIcon from "../icons/chatIcon";
import MarkIcon from "../icons/markIcon";
import { MarsIcon } from "lucide-react";
import { useState } from "react";
import GoodCheck from "../../../../assets/svg/goodCheck";
import RedX from "../../../../assets/svg/redX";
import DOMPurify from "dompurify";
import FocusIcon from "../icons/focusIcon";
import WarningGrey from "../../../../assets/svg/warningGrey";
import TranslateDropdown from "./translateDropdown";
import useLanguages from "../api/useLanguage";
import useTranslation from "../../../../hooks/useTranslation.jsx";
import wordStore from "../../../../mc/wordStore.json";
const GrammarV2 = ({ Aidata, isPersonal }) => {
  const { findText } = useTranslation(wordStore);
  const [selectedSection, setSelectedSection] = useState(1);
  const [selectedOperationIndex, setSelectedOperationIndex] = useState(null);
  const [transalate, setTranslate] = useState(null);
  const { translateLangData, handleTranslate } = useLanguages();
  const tabs = [
    {
      label: findText("Fixes"),
      value: 1,
      icon: ChatIcon,
    },
    {
      label: findText("General feedback"),
      value: 2,
      icon: ChatIcon,
    },
    {
      label: findText("Corrected version"),
      value: 3,
      icon: MarkIcon,
    },
  ].filter((item) => !(item?.value === 3 && Aidata?.score >= 100));
  const getSeverityInfo = (severity) => {
    switch (severity.toLowerCase()) {
      case "high":
      case "critical":
        return {
          color: "#E53E3E",
          label: "High",
          bgColor: "#FEEEEE",
        };
      case "medium":
      case "moderate":
        return {
          color: "#00C2C2",
          label: "Medium",
          bgColor: "#E5F9F9",
        };
      case "low":
      case "minor":
        return {
          color: "#FEBF10",
          label: "Low",
          bgColor: "#FFF9E7",
        };
      default:
        return {
          color: "#718096",
          label: "Unknown",
          bgColor: "#EDF2F7",
        };
    }
  };
  const formatErrorType = (type) => {
    const formatted = type.replace(/([A-Z])/g, " $1").trim();
    return `${formatted.toLowerCase()} error`;
  };
  const response = Aidata?.data;
  const feedbackIssues = response?.issues;
  const getSelectedOperations = () => {
    if (typeof selectedOperationIndex !== "number") return null;
    return response?.operations?.[selectedOperationIndex];
  };
  const selectOperation = getSelectedOperations();
  const mappedFeekback = () => {
    if (feedbackIssues?.length) {
      const list = [];
      feedbackIssues?.forEach((item) => {
        if (item?.type) {
          list.push(formatErrorType(item?.type));
        }
        if (item?.severity) {
          const info = getSeverityInfo(item?.severity);
          list.push(info?.label);
        }
        if (item?.message) {
          list.push(item?.message);
        }
        if (item?.suggestion) {
          list.push(item?.suggestion);
        }
      });
      list.push("Correction");
      return list;
    }
    return [];
  };
  const feedbackToTranslate = mappedFeekback();
  const findTranlatedWord = (label) => {
    if (!label) return "";
    const word = transalate?.find((item) => item?.text === label);
    return word?.value || label;
  };
  return (
    <ModelComtainer>
      <ModelContent>
        <GrammarHeader>
          <div className="instruction">
            <HandIcon />
            <p>
              {findText(
                "Click on the words / punctuation marks highlighted in red to see detailed feedback",
              )}
            </p>
          </div>
          <GrammarV2HeaderContent>
            {response && (
              <GrammarV2HeaderContentWrapper>
                {(() => {
                  const result = [];
                  let currentIndex = 0;
                  const replaceOperations = response.operations
                    .map((op, index) => ({
                      ...op,
                      operationIndex: index,
                    }))
                    .filter((op) => op.type === "replace")
                    .sort((a, b) => a.originalStart - b.originalStart);
                  while (currentIndex < response.originalText.length) {
                    const currentOperation = replaceOperations.find(
                      (op) => op.originalStart === currentIndex,
                    );
                    if (currentOperation) {
                      const operationText = response.originalText.slice(
                        currentOperation.originalStart,
                        currentOperation.originalEnd,
                      );
                      const isActive =
                        selectedOperationIndex ===
                        currentOperation.operationIndex;
                      result.push(
                        <span
                          key={`operation-${currentOperation.operationIndex}`}
                          className={isActive ? "active" : "error"}
                          onClick={() =>
                            setSelectedOperationIndex(
                              currentOperation.operationIndex,
                            )
                          }
                        >
                          {operationText}
                        </span>,
                      );
                      currentIndex = currentOperation.originalEnd;
                    } else {
                      const nextOperation = replaceOperations.find(
                        (op) => op.originalStart > currentIndex,
                      );
                      const endIndex = nextOperation
                        ? nextOperation.originalStart
                        : response.originalText.length;
                      const normalText = response.originalText.slice(
                        currentIndex,
                        endIndex,
                      );
                      if (normalText) {
                        result.push(
                          <span key={`normal-${currentIndex}`}>
                            {normalText}
                          </span>,
                        );
                      }
                      currentIndex = endIndex;
                    }
                  }
                  return result;
                })()}
              </GrammarV2HeaderContentWrapper>
            )}
          </GrammarV2HeaderContent>
          <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>{tab.label}</p>
              </li>
            ))}
          </ul>
        </GrammarHeader>
        <GrammarV2Content>
          <GrammarV2ContentWrapper>
            {selectedSection === 2 &&
              isPersonal &&
              feedbackIssues?.length > 0 && (
                <GrammarV2ContentWrapperTranslate>
                  <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);
                      } else {
                        setTranslate(null);
                      }
                    }}
                  />
                </GrammarV2ContentWrapperTranslate>
              )}
            {selectedSection === 1 && selectOperation && (
              <div className="feedback_section">
                <div className="failed">
                  <RedX />
                  <span>
                    {response?.originalText?.slice(
                      selectOperation?.originalStart,
                      selectOperation?.originalEnd,
                    )}
                  </span>
                </div>
                <div className="correct">
                  <GoodCheck />
                  <span>{selectOperation?.text}</span>
                </div>
              </div>
            )}
            {selectedSection === 2 && (
              <GrammarV2Feedback>
                <GrammarV2FeedbackList>
                  {feedbackIssues?.map((issue) => {
                    const info = getSeverityInfo(issue?.severity);
                    const labelType = formatErrorType(issue?.type);
                    return (
                      <li>
                        <div
                          className="grammar-v2_feekback_header"
                          style={{
                            background: info?.bgColor,
                          }}
                        >
                          <p>
                            {transalate
                              ? findTranlatedWord(labelType)
                              : labelType}
                          </p>
                          <div className="grammar-v2_feekback_header-status">
                            <span
                              style={{
                                color: info?.color,
                              }}
                            >
                              {transalate
                                ? findTranlatedWord(info?.label)
                                : findText(info?.label)}
                            </span>
                            <FocusIcon color={info?.color} />
                          </div>
                        </div>
                        <p className="grammar-v2_feekback-text">
                          {transalate
                            ? findTranlatedWord(issue?.message)
                            : issue?.message}
                        </p>
                        <div className="grammar-v2_feekback-correction_section">
                          <p className="grammar-v2_feekback-label">
                            {transalate
                              ? findTranlatedWord("Correction")
                              : findText("Correction")}
                            :
                          </p>
                          <p className="grammar-v2_feekback-text">
                            {transalate
                              ? findTranlatedWord(issue?.suggestion)
                              : issue?.suggestion}
                          </p>
                        </div>
                      </li>
                    );
                  })}
                </GrammarV2FeedbackList>
              </GrammarV2Feedback>
            )}
            {selectedSection === 3 && (
              <div className="correct_section">
                <div className="warning">
                  <WarningBlueIcon />
                  <p>{findText("Introduced words are highlighted in green")}</p>
                </div>
                <CorrectVersion response={response} />
              </div>
            )}
          </GrammarV2ContentWrapper>
        </GrammarV2Content>
      </ModelContent>
    </ModelComtainer>
  );
};
const CorrectVersion = ({ response }) => {
  if (!response) return null;
  const [formattedCorrectedCopy, setFormattedCorrectedCopy] = useState("");
  const processOperations = useCallback((operations, correctedText) => {
    if (!operations?.length) return correctedText;
    let modifiedText = correctedText;
    const insertOperations = operations?.filter((op) => op?.type === "insert");
    const sortedInserts = insertOperations.sort(
      (a, b) => b?.correctedStart - a?.correctedStart,
    );
    sortedInserts?.forEach((operation, index) => {
      const { text, correctedStart, correctedEnd } = operation;
      const beforeText = modifiedText?.slice(0, correctedStart);
      const insertedText = modifiedText?.slice(correctedStart, correctedEnd);
      const afterText = modifiedText?.slice(correctedEnd);
      if (insertedText === text) {
        modifiedText =
          beforeText +
          `<span class="corrected">${insertedText}</span>` +
          afterText;
        console.log(
          `✓ Highlighted inserted text: "${text}" at position ${correctedStart}-${correctedEnd}`,
        );
      } else {
        console.warn(
          `✗ Text mismatch for insert operation. Expected: "${text}", Found: "${insertedText}"`,
        );
      }
    });
    return DOMPurify.sanitize(modifiedText);
  }, []);
  useEffect(() => {
    if (!response) {
      setFormattedCorrectedCopy("");
      return;
    }
    const { operations, correctedText } = response;
    const processedText = processOperations(operations, correctedText);
    setFormattedCorrectedCopy(processedText);
  }, [response, processOperations]);
  return (
    <GrammarV2Correct>
      <p
        dangerouslySetInnerHTML={{
          __html: formattedCorrectedCopy,
        }}
      ></p>
    </GrammarV2Correct>
  );
};
const WarningBlueIcon = () => (
  <svg
    xmlns="http://www.w3.org/2000/svg"
    width="18"
    height="18"
    viewBox="0 0 18 18"
    fill="none"
  >
    <path
      d="M8.16406 4.83073H9.83073V6.4974H8.16406V4.83073ZM8.16406 8.16406H9.83073V13.1641H8.16406V8.16406ZM8.9974 0.664062C4.3974 0.664062 0.664062 4.3974 0.664062 8.9974C0.664062 13.5974 4.3974 17.3307 8.9974 17.3307C13.5974 17.3307 17.3307 13.5974 17.3307 8.9974C17.3307 4.3974 13.5974 0.664062 8.9974 0.664062ZM8.9974 15.6641C5.3224 15.6641 2.33073 12.6724 2.33073 8.9974C2.33073 5.3224 5.3224 2.33073 8.9974 2.33073C12.6724 2.33073 15.6641 5.3224 15.6641 8.9974C15.6641 12.6724 12.6724 15.6641 8.9974 15.6641Z"
      fill="#00C2C2"
    />
  </svg>
);
export default GrammarV2;
