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;
    }
    // Fetch welcome message if no messages are present
    if (messages.length === 0) {
      fetchWelcomeMessage();
    }
  }, [messages]);

  const fetchWelcomeMessage = async () => {
    // Retrieve user email and bot name if they are stored
    const userEmail = "meet_nagadia@ext.icicipruamc.com";
    const botName = "HR-Assist"; // Setting your bot name here

    try {
      const response = await axios.post(`${baseurl}/welcome-message`, {
        user_email: userEmail,
        bot_name: botName,
      });

      // Assuming your backend returns the message correctly in response.data
      if (response.data) {
        setMessages((prevMessages) => {
          const updatedMessages = [
            ...prevMessages,
            { message: response.data.message, prompt: "Welcome" },
          ];
          sessionStorage.setItem("hr_messages", JSON.stringify(updatedMessages));
          return updatedMessages;
        });
      }
    } catch (error) {
      console.error("Error fetching welcome message:", error);
    }
  };

  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;


This is the UI code.


@app.route("/welcome-message", methods=['POST'])
def welcome_message():
    try:
        data = request.get_json()
        user_email = data['user_email']
        bot_name = data['bot_name']

        response = Response(get_welcome_message(bot_name=bot_name, user_email=user_email), mimetype="text/event-stream")
        response.headers["X-Accel-Buffering"] = "no"
        print(f"/welcome-message - Response Sent to user: {user_email}")
        print(response)
        return response
    except Exception as e:
        print(f"/welcome-message - Response Not Sent to user: {user_email}")


This is the backend code.

I want that when the page if there is no conversation, we show welcome message fetched from the api, correct the UI code accordingly, also make sure, if there is no conversation then we dont show the first query box from user side, it should be from bot side when we show welcome message. dont change rest of funcnality