import React from "react";
import { useParams } from "react-router-dom";
import WireframeSDK from "@/utils/WireframeSDK";
import { ImSpinner10 } from "react-icons/im";
import { BsArrowReturnLeft } from "react-icons/bs";
import { GlobalContext, showToast } from "@/context/Global";
import MkdSDK from "@/utils/MkdSDK";
import { AuthContext, tokenExpireError } from "@/context/Auth";

let sdk = new MkdSDK();
let wSDk = new WireframeSDK();
const AskGptAdminSowTablePage = () => {
  const { dispatch } = React.useContext(AuthContext);
  const [answers, setAnswers] = React.useState([]);
  const [questions, setQuestions] = React.useState("");
  const [isLoadingBtn, setIsLoadingBtn] = React.useState(false);
  const questionsRef = React.useRef(null);
  const { id } = useParams();
  const [transcripts, setTranscripts] = React.useState([]);
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const [cursorPosition, setCursorPosition] = React.useState({
    line: 1,
    col: 0,
  });

  React.useEffect(function () {
    (async function () {
      try {
        sdk.setTable("sow");
        const result = await sdk.callRestAPI({ id: Number(id) }, "GET");
        if (!result.error) {
          const { model } = result;
          setTranscripts(
            model.transcripts === null ? [] : JSON.parse(model.transcripts)
          );
        }
      } catch (error) {
        tokenExpireError(dispatch, error.message);
      }
    })();
  }, []);

  const handleOnChange = (event) => {
    setQuestions(event.target.value);
    const { value, selectionStart, selectionEnd } = event.target;
    const lines = value.substr(0, selectionStart).split("\n");
    const line = lines.length;
    const col = lines[lines.length - 1].length;
    if (selectionEnd === selectionStart && value[selectionStart] === "\n") {
      setCursorPosition({ line: line + 1, col: 0 });
    } else {
      setCursorPosition({ line, col });
    }
    requestAnimationFrame(() => {
      const lineHeight = parseFloat(
        getComputedStyle(questionsRef.current).lineHeight
      );
      questionsRef.current.scrollTop = (cursorPosition.line - 1) * lineHeight;
    });
  };

  const handleKeyDown = (event) => {
    if (!event.shiftKey && event.key === "Enter") {
      event.preventDefault();
      handleAskQuestion(event);
      return;
    }
    if (event.shiftKey && event.key === "Enter") {
      event.preventDefault();
      const newInstructions = `${questions.substring(
        0,
        event.target.selectionStart
      )}\n${questions.substring(event.target.selectionStart)}`;
      setQuestions(newInstructions);
      setCursorPosition({ line: cursorPosition.line + 1, col: 0 });
    }
  };

  const handleAskQuestion = async (event, from) => {
    if (event.key === "Enter" || from === "onClick") {
      const question = questions;
      setIsLoadingBtn(true);
      try {
        let prompt = answers.length
          ? [
              {
                role: "system",
                content: `${JSON.stringify(transcripts)}  Use the above technical requirements given above as knowledge to chat with the user, `,
              },
              {
                role: "assistant",
                content: `${answers[answers.length - 1]?.answer}`,
              },
              {
                role: "user",
                content: questions,
              },
            ]
          : [
              {
                role: "system",
                content: `${JSON.stringify(transcripts)}  Use the above technical requirements given above as knowledge to chat with the user, `,
              },
              {
                role: "user",
                content: questions,
              },
            ];

        const result = await wSDk.askGptCustom(prompt);
        if (!result.error) {
          const obj = {
            id: answers?.length + 1,
            question,
            answer: result?.message?.message?.content,
          };
          setAnswers([...answers, obj]);
        }
      } catch (error) {
        showToast(globalDispatch, error?.message, 2000, "error");
      }
      setQuestions("");
      setIsLoadingBtn(false);
    }
  };

  return (
    <div className="mx-auto flex h-full w-full max-w-full flex-col overflow-hidden rounded-md bg-white shadow-md">
      <header className="flex items-center justify-between border-b p-4">
        <h2 className="text-lg font-semibold">Ask Requirement Bot</h2>
      </header>

      <div className="mx-auto mt-5 h-[65vh] w-[80%] overflow-y-auto rounded-lg border border-[#828282] px-4 pt-5">
        <div className="flex items-start gap-3 space-y-2">
          <div className=" mt-2 h-8 w-8 rounded-full bg-blue-400" />
          <div>
            <h3 className="text-xl font-semibold">AI</h3>
            <p className="text-base">How can I help you today?</p>
          </div>
        </div>
        {answers?.map((qna) => (
          <>
            <div className="flex flex-row-reverse items-start gap-3 space-y-2 text-right">
              <div className=" mt-2 !h-8 min-h-[2rem] !w-8 min-w-[2rem] rounded-full bg-gray-400" />
              <div>
                <h3 className="text-xl font-semibold">You</h3>
                <div className="min-w-fit max-w-[70%] pl-20">
                  <p className="text-base">{qna?.question}</p>
                </div>
              </div>
            </div>
            <div className="flex items-start gap-3 space-y-2 pb-5">
              <div className=" mt-2 !h-8 min-h-[2rem] !w-8 min-w-[2rem] rounded-full bg-blue-400" />
              <div>
                <h3 className="text-xl font-semibold">AI</h3>
                <div className="min-w-fit max-w-[70%] pr-20">
                  <p className="text-base">{qna?.answer}</p>
                </div>
              </div>
            </div>
          </>
        ))}
      </div>
      <div className="relative z-10 mx-auto my-5  flex w-[80%] items-center justify-center">
        <textarea
          placeholder="Ask Your Requirements"
          name="question"
          onKeyDown={(event) => handleKeyDown(event)}
          value={questions}
          className="scrollbar-hide flex-1 resize-none overflow-auto whitespace-pre-wrap rounded-lg py-5 pl-6 pr-20"
          ref={questionsRef}
          onChange={(event) => handleOnChange(event)}
          rows={1}
          maxLength={300}
        />
        <button
          disabled={isLoadingBtn}
          onClick={(event) => handleAskQuestion(event, "onClick")}
          className="absolute bottom-0 right-0 rounded-lg rounded-l-none px-4 py-1.5 text-white shadow-sm"
        >
          <span className="block p-3">
            {isLoadingBtn ? (
              <ImSpinner10
                style={{ fontSize: 27 }}
                className="animate-spin font-bold text-gray-700"
              />
            ) : (
              <BsArrowReturnLeft
                style={{ fontSize: 26 }}
                className="font-bold text-gray-700"
              />
            )}
          </span>
        </button>
      </div>
    </div>
  );
};

export default AskGptAdminSowTablePage;
