import React, { useRef, useEffect, useState } from "react";
import { MdThumbDown, MdThumbUp } from "react-icons/md";
import axios from "axios";
import "./index.css";
import baseurl from "../../api/url";
import Markdown from "react-markdown";
import remarkGfm from "remark-gfm";
import { keycloak } from "../../../../keycloak";

const Chat = () => {
  const bottomEl = useRef(null);
  const [messages, setMessages] = useState(
    JSON.parse(sessionStorage.getItem("hr_messages") || "[]")
  );
  const [query, setquery] = useState("");
  const [disabled, makeDisabled] = useState(false);

  // const [prompt, setprompt] = useState({ initital_prompt: "", new_prompt: "" });

  // if (keycloak.authenticated){
  //   keycloak.loadUserInfo().then((data)=>{ console.log("This is from chat page",  data)})
  //   console.log(keycloak.profile)
  // }

  useEffect(() => {
    // Scroll to the bottom when the component mounts or whenever content changes
    if (bottomEl.current) {
      bottomEl.current.scrollTop = bottomEl.current.scrollHeight;
    }
  }, [messages]);

  const sendChatRequest = async (mail) => {
    // Using a callback with setMessages to ensure working with the updated state
    console.log(mail);
    const mail2 = mail;
    var index = -1;
    setMessages((prevMessages) => {
      index = prevMessages.length;
      console.log(mail);
      const updatedMessages = [
        ...prevMessages,
        { message: mail2, prompt: query },
      ];
      sessionStorage.setItem("hr_messages", JSON.stringify(updatedMessages));
      console.log("setstate: ", updatedMessages);
      return updatedMessages;
    });

    console.log("justaftersetstate: ", messages);

    var context_history = [];

    for (var message of messages) {
      context_history.push({ role: "user", content: message.message });
      if (message.api_output) {
        if (message.api_output.options) {
          context_history.push({
            role: "assistant",
            content:
              "Please select any options of the following: \n" +
              message.api_output.options.files.toString(),
          });
        } else {
          context_history.push({
            role: "assistant",
            content: message.api_output.text,
          });
        }
      }
    }

    var context_file = "";
    if (mail.startsWith("file: ")) {
      context_file = mail.replace("file: ", "");
      console.log("file_context: ", context_file);
      for (var each_message of context_history.reverse()) {
        if (each_message.role == "user") {
          mail = each_message.content;
          console.log("mymail:", mail);
          break;
        }
      }
    }
    try {
      setquery("");
      const res = await fetch(baseurl + "/answer", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          prompt: mail,
          history: context_history,
          file: context_file !== "" ? context_file : undefined,
          user_email: JSON.parse(localStorage.getItem("user")).email,
          stream: true,
        }),
      });
      if (res.status == 202) {
        console.log("I am here");
        const reader = res.body.getReader();
        const decoder = new TextDecoder("utf-8");

        const { value, done } = await reader.read();
        const chunk = decoder.decode(value, { stream: true });
        console.log(JSON.parse(chunk));
        setMessages((prevMessages) => {
          const updatedMessages = [...prevMessages];
          if (!updatedMessages[index].api_output) {
            updatedMessages[index].api_output = { options: JSON.parse(chunk) };
          }
          sessionStorage.setItem(
            "hr_messages",
            JSON.stringify(updatedMessages)
          );

          return updatedMessages;
        });
      } else {
        const reader = res.body.getReader();
        const decoder = new TextDecoder("utf-8");

        let buffer = "";

        while (true) {
          const { value, done } = await reader.read();
          if (done) break;
          const chunk = decoder.decode(value, { stream: true });
          buffer += chunk;

          while (buffer.includes("\n\n")) {
            const newlineIndex = buffer.indexOf("\n\n");
            const chunk_part = buffer.slice(0, newlineIndex);
            buffer = buffer.slice(newlineIndex + 1);
            const chunk_part_reformatted = chunk_part
              .trim()
              .replace("data: ", "");
            if (chunk_part_reformatted) {
              // console.log(chunk_part);

              try {
                const chunk_part_json = JSON.parse(chunk_part_reformatted);
                setMessages((prevMessages) => {
                  const updatedMessages = [...prevMessages];
                  if (!updatedMessages[index].api_output) {
                    updatedMessages[index].api_output = { text: "" };
                  }
                  updatedMessages[index].api_output.text +=
                    chunk_part_json.text;
                  updatedMessages[index].api_output.answer_id =
                    chunk_part_json.conversationid;
                  updatedMessages[index].api_output.pages =
                    chunk_part_json.pages;
                  updatedMessages[index].api_output.link = chunk_part_json.link;
                  sessionStorage.setItem(
                    "hr_messages",
                    JSON.stringify(updatedMessages)
                  );

                  return updatedMessages;
                });
              } catch (error) {
                console.error("Error parsing JSON:", error);
              }
            }
          }
        }
      }
    } catch (error) {
      console.error("Error:", error);
    }
  };

  const handleUserQueryChange = (query) => {
    // Using a callback with setMessages to ensure working with the updated state
    setquery(query.target.value);
  };

  const change_feedback = (item, index, feedback) => {
    // Using a callback with setMessages to ensure working with the updated state
    axios
      .post(baseurl + "/change_feedback", {
        feedback: feedback,
        conversationid: item.api_output.answer_id,
      })
      .then((value) => {
        setMessages((prevMessages) => {
          const updatedMessages = [...prevMessages];
          updatedMessages[index].api_output.feedback = feedback;
          return updatedMessages;
        });
      })
      .catch((error) => alert("Some error occured"));
  };

  return (
    <div className="flex h-[89vh] flex-col">
      <div className="text-lg flex justify-between">
        <strong>HR-Docs</strong>
        <button
          className="ml-0.5 rounded-lg px-6 py-1 text-lg text-white"
          // className="ml-4 rounded-lg bg-gradient-to-r from-orange-400 py-3 text-lg text-white rounded"
          style={{
            background: "linear-gradient(to right, #ff0000, #990000)",
            color: "white",
            padding: "5px 10px",
            borderRadius: "5px",
            border: "none",
            cursor: "pointer",
          }}
          onClick={() => {
            setMessages([]);
            sessionStorage.setItem("hr_messages", "[]");
          }}
        >
          Clear Chat
        </button>
      </div>
      <div
        ref={bottomEl}
        className="h-[80%] flex flex-col flex-grow overflow-y-auto"
      >
        {messages.length !== 0 ? (
          messages.map((item, index) => {
            //             color_feedback = ""
            //             if (item.api_output.feedback == "NEGATIVE"){
            //               color_feedback =
            //             }else if (item.api_output.feedback == "POSITIVE"){
            // color_feedback =
            //             }
            return (
              <div className="flex flex-col space-y-4 p-6">
                <div className="max-w-75p flex items-center self-end rounded-xl rounded-lg rounded-tr bg-blueSecondary py-4 px-6 text-white ">
                  {/* <p className="text-lg" style={{ whiteSpace: "pre-line" }}> */}
                  {/* {item.message} */}
                  <Markdown
                    className="prose text-white"
                    remarkPlugins={[remarkGfm]}
                  >
                    {item.message}
                  </Markdown>
                  {/* </p> */}
                </div>
                {item.api_output !== undefined ? (
                  <>
                    <div className="group relative flex items-end">
                      {item.api_output?.text && (
                        <>
                          <div className="flex items-center self-start rounded-xl rounded-lg rounded-tl bg-lightPrimary py-4 px-6">
                            <Markdown
                              className="prose"
                              remarkPlugins={[remarkGfm]}
                            >
                              {item.api_output?.text}
                            </Markdown>
                          </div>
                          <MdThumbUp
                            className="h-8 w-8 cursor-pointer opacity-0 transition-opacity duration-300 group-hover:opacity-100 sticky top-0"
                            style={{
                              color:
                                item.api_output.feedback == "POSITIVE"
                                  ? "green"
                                  : "",
                            }}
                            onClick={() =>
                              change_feedback(item, index, "POSITIVE")
                            }
                          />
                          <br />
                          <MdThumbDown
                            className="h-8 w-8 cursor-pointer opacity-0 transition-opacity duration-300 group-hover:opacity-100 sticky top-0"
                            style={{
                              color:
                                item.api_output.feedback == "NEGATIVE"
                                  ? "red"
                                  : "",
                            }}
                            onClick={() =>
                              change_feedback(item, index, "NEGATIVE")
                            }
                          />
                        </>
                      )}
                      {item.api_output?.options && (
                        <>
                          <div className="flex flex-col items-center self-start rounded-xl rounded-lg rounded-tl bg-lightPrimary py-4 px-6">
                            <Markdown
                              className="prose"
                              remarkPlugins={[remarkGfm]}
                            >
                              {"### " + item.api_output.options.messgage}
                            </Markdown>
                            {item.api_output.options.files.length !== 0 ? (
                              item.api_output.options.files.map(
                                (fileitem, index) => {
                                  return (
                                    <>
                                      <br />
                                      <button
                                        className="rounded-lg px-6 py-3 text-m text-white"
                                        // className="ml-4 rounded-lg bg-gradient-to-r from-orange-400 py-3 text-lg text-white rounded"
                                        style={{
                                          background:
                                            "linear-gradient(to right, #f2994a, #d94e44)",
                                          color: "white",
                                          padding: "10px 20px",
                                          borderRadius: "5px",
                                          border: "none",
                                          cursor: "pointer",
                                        }}
                                        onClick={() => {
                                          sendChatRequest(
                                            "file: " + fileitem.toString()
                                          );
                                        }}
                                      >
                                        {fileitem.toString()}
                                      </button>
                                    </>
                                  );
                                }
                              )
                            ) : (
                              <div className="flex items-center self-start rounded-xl rounded-lg rounded-tl bg-lightPrimary py-4 px-6">
                                <Markdown
                                  className="prose"
                                  remarkPlugins={[remarkGfm]}
                                >
                                  {"#Some error occured"}
                                </Markdown>
                              </div>
                            )}
                          </div>
                          <div className="flex items-center self-start rounded-xl rounded-lg rounded-tl bg-lightPrimary py-4 px-6">
                            <Markdown
                              className="prose"
                              remarkPlugins={[remarkGfm]}
                            >
                              {item.api_output?.text}
                            </Markdown>
                          </div>
                          <MdThumbUp
                            className="h-8 w-8 cursor-pointer opacity-0 transition-opacity duration-300 group-hover:opacity-100 sticky top-0"
                            style={{
                              color:
                                item.api_output.feedback == "POSITIVE"
                                  ? "green"
                                  : "",
                            }}
                            onClick={() =>
                              change_feedback(item, index, "POSITIVE")
                            }
                          />
                          <br />
                          <MdThumbDown
                            className="h-8 w-8 cursor-pointer opacity-0 transition-opacity duration-300 group-hover:opacity-100 sticky top-0"
                            style={{
                              color:
                                item.api_output.feedback == "NEGATIVE"
                                  ? "red"
                                  : "",
                            }}
                            onClick={() =>
                              change_feedback(item, index, "NEGATIVE")
                            }
                          />
                        </>
                      )}
                    </div>

                    {item.api_output?.pages !== undefined &&
                    item.api_output?.pages !== "NA" &&
                    !item.api_output?.text.includes("really sorry") ? (
                      <div className="flex items-center self-start rounded-xl rounded-lg rounded-tl bg-lightPrimary">
                        <a
                          href={item.api_output?.link}
                          className="text-blueSecondary underline"
                          target="_blank"
                        >
                          <strong>{item.api_output?.pages}</strong>
                        </a>
                      </div>
                    ) : (
                      <></>
                    )}
                  </>
                ) : (
                  <div className="group relative flex items-center">
                    <div className="flex items-center self-start rounded-xl rounded-tl bg-white py-4 px-6">
                      <div className="typing">
                        <div className="typing__dot"></div>
                        <div className="typing__dot"></div>
                        <div className="typing__dot"></div>
                      </div>
                    </div>
                  </div>
                )}
              </div>
            );
          })
        ) : (
          <div className="default-text max-h-[76vh] text-2xl">
            <p>Paste a query in textbox below.</p>
          </div>
        )}
        {/* <div ref={bottomEl}></div> */}
      </div>

      <div className="h-[10%] flex items-center">
        <div className="mr-2 w-full text-lg">
          <textarea
            id="body"
            name="body"
            className="mr-2 w-full rounded-lg border border-gray-300 px-4 py-3 text-lg"
            placeholder="Enter your query..."
            rows="1"
            cols="50"
            value={query}
            onChange={handleUserQueryChange}
            onKeyDown={(e) => {
              if (e.key === "Enter" && e.shiftKey === false) {
                e.preventDefault();
                if (!(query === "")) {
                  sendChatRequest(query);
                } else {
                  alert("Please enter query");
                }
              }
            }}
          ></textarea>
        </div>
        <button
          className="ml-0.5 rounded-lg px-6 py-3 text-lg text-white"
          // className="ml-4 rounded-lg bg-gradient-to-r from-orange-400 py-3 text-lg text-white rounded"
          style={{
            background: "linear-gradient(to right, #f2994a, #d94e44)",
            color: "white",
            padding: "10px 20px",
            borderRadius: "5px",
            border: "none",
            cursor: "pointer",
          }}
          onClick={() => {
            if (!(query === "")) {
              sendChatRequest(query);
            } else {
              alert("Please enter query");
            }
          }}
        >
          Send
        </button>
      </div>
    </div>
  );
};

export default Chat;


I want that as our page is loaded, we call a backend api for displaying the message. after that the chat should continue as usual. if the chat is already there, then I dont want to show the welcome message