import React, { useState } from "react";
import CursorClickIcon from "./assets/cursorClick";
import styled from "styled-components";
import { IoCloseOutline } from "react-icons/io5";
import { FaCheck } from "react-icons/fa6";
import ButtonComponent from "../button";
import useTranslation from "../../hooks/useTranslation.jsx";
import wordStore from "../../mc/wordStore.json";
const Grammer = ({ data, hideScore }) => {
  const { findText } = useTranslation(wordStore);
  const [selected, setSelected] = useState(null);
  const [showVersion, setShowVersion] = useState(null);
  const feedbackCorrection = data["Correction Operations (Optional)"] || [];
  const originalText = data["Original Speech"] || "";
  const correctText = data["Grammatical Correct Version"] || "";
  const getFeekbackResult = () => {
    const result = [];
    let positionCounter = 1; // Tracks the word position in the text
    let correctionIndex = 0; // Tracks the current correction
    let words = originalText?.split(/\s+/) || []; // Split text into words
    let wordIndex = 0; // Tracks the current word being processed

    while (wordIndex <= words?.length) {
      const word = words[wordIndex];
      const correction = feedbackCorrection[correctionIndex];
      if (
        correction &&
        correction?.operation === "substituted" &&
        // Handle substitution
        words
          .slice(
            wordIndex,
            wordIndex + correction?.original_word.split(' ').length,
          )
          .join(' ') === correction?.original_word
      ) {
        result.push({
          text: correction?.original_word,
          correct: correction?.replacement_word,
          position: positionCounter,
          operation: correction?.operation,
        });
        wordIndex += correction?.original_word.split(' ').length || 0;
        correctionIndex++;
        positionCounter++;
      } else if (correction && correction?.operation === 'inserted') {
        result.push({
          text: correction?.word,
          correct: correction?.word,
          // Insert the new word
          position: positionCounter,
          operation: correction?.operation,
        });
        correctionIndex++;
        positionCounter++;
      } else {
        if (word !== undefined) {
          result.push({
            text: word,
          });
        }
        wordIndex++;
      }
    }
    return result;
  };
  const getCorrectResult = () => {
    const result = [];
    let correctionIndex = 0;
    let words = correctText.split(/\s+/);
    let wordIndex = 0;
    while (wordIndex < words.length) {
      const word = words[wordIndex];
      const correction = feedbackCorrection[correctionIndex];
      if (
        correction &&
        correction?.operation === 'substituted' &&
        words
          .slice(
            wordIndex,
            wordIndex + correction?.replacement_word.split(' ').length,
          )
          .join(' ') === correction?.replacement_word
      ) {
        result.push({
          text: correction?.replacement_word,
          highlight: true,
        });
        wordIndex += correction?.replacement_word.split(' ').length;
        correctionIndex++;
      } else if (correction && correction?.operation === 'inserted') {
        result.push({
          text: correction?.word,
          highlight: true,
        });
        correctionIndex++;
      } else {
        result.push({
          text: word,
        });
        wordIndex++;
      }
    }
    return result;
  };
  const generateParagraph = (data) => {
    let paragraph = "<p>";
    data?.forEach((item) => {
      if (item?.highlight) {
        paragraph += `<span>${item?.text}</span> `;
      } else {
        paragraph += `${item?.text} `;
      }
    });
    paragraph = paragraph?.trim() + "</p>";
    return paragraph;
  };
  return (
    <Container>
      {showVersion && (
        <WordsModal
          value={showVersion?.value}
          isCorrect={showVersion?.isCorrect}
          onClose={() => {
            setShowVersion(null);
          }}
        />
      )}
      <Header>
        <div className="info">
          <CursorClickIcon />
          <p>
            {findText(
              "Click on the words/sentences highlighted in red to see feedback"
            )}
          </p>
        </div>
        {!hideScore && (
          <p>
            {findText("Points:")}
            <span>{data?.["Grammar Score"] || 0}</span>
          </p>
        )}
      </Header>
      <Content>
        <div className="text_content">
          {getFeekbackResult()?.map((value, idx) => (
            <span
              key={idx}
              onClick={() => {
                if (value?.position) setSelected(value);
              }}
              className={`${value?.position ? 'error' : ''}`}
            >
              {' '}
              {value?.position && <span>{value?.position}</span>} {value?.text}
            </span>
          ))}
        </div>
        {selected && (
          <div className="feedback_content">
            <h3>{findText("Feedback:")}</h3>
            <div className="reply">
              {selected?.operation !== 'inserted' && (
                <div className="row red">
                  <IoCloseOutline color="#F95454" />
                  <p className="red">
                    <span>{selected?.position}</span>
                    {selected?.text}
                  </p>
                </div>
              )}

              <div className="row">
                <FaCheck color="#29D1D1" />
                <p>{selected?.correct}</p>
              </div>
            </div>
          </div>
        )}
      </Content>
      <ButtonWrapper>
        <span
          onClick={() => {
            setShowVersion({
              value: `<p>${originalText}</p>`,
            });
          }}
        >
          <ButtonComponent text={findText("View script")} type="secondary" />
        </span>
        <span
          onClick={() => {
            const correctResults = getCorrectResult();
            const value = generateParagraph(correctResults);
            setShowVersion({
              value,
              isCorrect: true,
            });
          }}
        >
          <ButtonComponent
            text={findText("View corrected version")}
            type="secondary"
          />
        </span>
      </ButtonWrapper>
    </Container>
  );
};
export default Grammer;
const WordsModal = ({ onClose, isCorrect, value }) => {
  const { findText } = useTranslation(wordStore);
  return (
    <ModalWrapper isOpen>
      <ModalComntainer>
        <span className="close_btn" onClick={onClose}>
          <IoCloseOutline color="#000" size={24} />
        </span>
        <div className="word_wrapper">
          {isCorrect && (
            <div className="header">
              <h4>{findText("Corrected version")}</h4>
              <p>{findText("Introduced words are highlighted in green")}</p>
            </div>
          )}
          <div
            className="content"
            dangerouslySetInnerHTML={{
              __html: value,
            }}
          ></div>
        </div>
      </ModalComntainer>
    </ModalWrapper>
  );
};
const ModalComntainer = styled.div`
  width: 610px;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 10px;
  .close_btn {
    width: 40px;
    height: 40px;
    display: grid;
    place-items: center;
    background-color: #fff;
    cursor: pointer;
    border-radius: 50%;
  }
  .word_wrapper {
    border-radius: 30px;
    background: #fff;
    width: 100%;
    padding: 48px;
    min-height: 520px;
    display: flex;
    flex-direction: column;
    gap: 20px;
    .header {
      h4 {
        border-radius: 10px 10px 0px 0px;
        background: #00c2c2;
        height: 32px;
        padding: 0 15px;
        display: flex;
        align-items: center;
        color: #fff;
        font-size: 16px;
        font-weight: 400;
      }
      p {
        border-radius: 0px 0px 10px 10px;
        background: #f5f7f7;
        height: 32px;
        padding: 0 15px;
        display: flex;
        align-items: center;
        color: #919494;

        font-size: 14px;
      }
    }
    .content {
      > p {
        color: #797979;
        font-size: 16px;
        line-height: 34px;
        span {
          color: #00c2c2;
        }
      }
    }
  }
`;
const Container = styled.div`
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 20px;
`;
const Header = styled.div`
  display: flex;
  align-items: center;
  justify-content: space-between;
  .info {
    display: flex;
    align-items: center;
    gap: 10px;
    p {
      color: #636666;
      font-size: 16px;
    }
  }
  > p {
    border-radius: 10px;
    height: 40px;
    width: 140px;
    background: #e5f9f9;
    display: flex;
    align-items: center;
    gap: 4px;
    justify-content: center;
    color: #636666;
    font-size: 16px;
    span {
      color: #00c2c2;
      font-size: 20px;
      font-weight: 700;
    }
  }
`;
const Content = styled.div`
  border-radius: 20px;
  background: #f9f9f9;
  padding: 20px;
  min-height: 400px;
  display: flex;
  flex-direction: column;
  width: 100%;
  gap: 32px;
  .text_content {
    flex: 1;
    span {
      color: #797979;
      font-size: 16px;
      line-height: 34px;
      &.error {
        display: inline-flex;
        align-items: center;
        color: #f95454;
        cursor: pointer;
        span {
          display: inline-flex;
          border-radius: 22.667px;
          align-items: center;
          background: rgba(249, 84, 84, 0.1);
          height: 16px;
          font-size: 14px;
          line-height: 14px;
          padding: 0 4px;
          color: #f95454;
        }
      }
    }
  }
  .feedback_content {
    width: 100%;
    padding: 15px;
    border-radius: 20px;
    background: #fff;
    h3 {
      color: #00c2c2;
      font-size: 16px;
      margin-bottom: 10px;
      line-height: 11px;
      padding-bottom: 10px;
      border-bottom: 1px solid #dfe5e5;
    }
    .reply {
      .row {
        display: flex;
        align-items: center;
        width: 100%;
        gap: 10px;
        p {
          font-size: 16px;
          color: #0d7d96;
          line-height: 34px;
          &.red {
            display: inline-flex;
            align-items: center;
            color: #f95454;
            cursor: pointer;
            span {
              display: inline-flex;
              border-radius: 22.667px;
              align-items: center;
              background: rgba(249, 84, 84, 0.1);
              height: 16px;
              font-size: 14px;
              line-height: 14px;
              padding: 0 4px;
              color: #f95454;
            }
          }
        }
      }
    }
  }
`;
const ButtonWrapper = styled.div`
  display: flex;
  align-items: center;
  gap: 20px;
  button {
    width: 233px;
    padding: 0;
    height: 44px;
  }
`;
const ModalWrapper = styled.div`
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  display: ${({ isOpen }) => (isOpen ? 'flex' : 'none')};
  align-items: center;
  justify-content: center;
  background-color: rgba(0, 0, 0, 0.6);
  z-index: 9999;
`;
