import React, { useState, useEffect, useRef } from "react";
import { Button } from "../Button";
import ClearIcon from "@mui/icons-material/Clear";
import SaveOutlinedIcon from "@mui/icons-material/SaveOutlined";
import SmartBotIcon from "../../assets/smartBotAlan.svg";
import CloseThreadIcon from "../../assets/close.svg";
import HomeIcon from "../../assets/chat-home-icon.svg";
import ChatInput from "./chatInput";
import { formatAMPM, getDateLabel } from "./utils";
import moment from "moment";
import { ChatbotModuleMenu } from "./chatbotModuleMenu";
export const ConversationScreen = ({
  userChats,
  setUserChats,
  onSendIconClick,
  conversation,
  isAssistantThinking,
  activeList,
  onLikeClick,
  onDislikeClick,
  inputText,
  handleRefresh,
  handleSaveChat,
  handleMicClick,
  suggestionBanner,
  isStopIcon,
  onStopIconClick,
  onCloseSuggestionBanner,
  showSuggestionBanner,
  customInputComponent,
}) => {
  const [input, setInput] = useState(inputText);
  const [conversationMessages, setConversationMessages] = useState([]);
  const [showThinkingResponseContent, setShowThinkingResponseContent] =
    useState([]);

  // Add ref for scrolling
  const conversationBodyRef = useRef(null);

  useEffect(() => {
    setInput(inputText);
  }, [inputText]);

  useEffect(() => {
    // Get the first conversation in the conversations object
    const conversationsObj = conversation?.conversations || {};
    const firstKey = Object.keys(conversationsObj)[0];
    const messagesArr = conversationsObj[firstKey]?.messages || [];
    const mapped = messagesArr?.map((msg) => ({
      ...msg,
      role: msg.userType === "bot" ? "assistant" : "user",
      text: msg.bodyText,
      type: msg.jsx ? "jsx" : msg.bodyType,
      formComponent: msg.bodyType === "form" ? msg.formComponent : undefined,
      tableComponent: msg.bodyType === "table" ? msg.tableComponent : undefined,
      timestamp:
        msg.timeStamp === ""
          ? ""
          : moment(msg.timeStamp, "DD-MM-YYYY HH:mm:ss").format(
              "MM-DD-YYYY HH:mm:ss"
            ),
      jsx: msg.jsx,
      thinkingResponse: msg.thinkingResponse,
    }));
    setConversationMessages(mapped);
  }, [conversation]);

  // Add useEffect to scroll to bottom when messages change
  useEffect(() => {
    if (conversationBodyRef.current) {
      conversationBodyRef.current.scrollTo({
        top: conversationBodyRef.current.scrollHeight,
        behavior: "smooth",
      });
    }
  }, [conversationMessages, isAssistantThinking, conversation]);

  const handleLikeClick = (chat, idx) => {
    chat.isAnimateLike = true;
    let timeout = setTimeout(() => {
      chat.isAnimateLike = false;
    }, 1000);
    onLikeClick?.(chat, idx);
    return () => clearTimeout(timeout);
  };

  const handleDislikeClick = (chat, idx) => {
    chat.isAnimateDislike = true;
    let timeout = setTimeout(() => {
      chat.isAnimateDislike = false;
    }, 1000);
    onDislikeClick?.(chat, idx);
    return () => clearTimeout(timeout);
  };

  const handleThinkingResponseClick = (idx) => {
    setShowThinkingResponseContent((prev) =>
      prev.includes(idx) ? prev.filter((i) => i !== idx) : [...prev, idx]
    );
  };

  return (
    <div className="conversation-screen-container">
      {/* Conversation body starts here  */}

      <div className={`conversation-body-container ${showSuggestionBanner ? "show-suggestion-banner" : ""}`} ref={conversationBodyRef}>
        {/* Date separators dynamically inserted below */}
        {conversationMessages.map((chat, idx) => {
          const prevMsg = conversationMessages[idx - 1];
          const showDateLabel =
            idx === 0 ||
            (chat.timestamp &&
              prevMsg.timestamp &&
              new Date(chat.timestamp).toDateString() !==
                new Date(prevMsg.timestamp).toDateString());

          return (
            <React.Fragment key={idx}>
              {showDateLabel && (
                <div className="time_stamp_badge_chat_container">
                  <div className="time_stamp_badge_chat">
                    {getDateLabel(chat.timestamp)}
                  </div>
                </div>
              )}
              {chat.role === "user" ? (
                <div className="user_chat_messages_container">
                  <div className="user_chat_message">
                    <div className="user_chat_message_text">{chat.text}</div>
                    <div className="time_chat">
                      {chat.timestamp
                        ? formatAMPM(new Date(chat.timestamp))
                        : ""}
                    </div>
                  </div>
                </div>
              ) : chat.role === "assistant" ? (
                <div className="assistant_chat_messages_container">
                  {chat.firstMessage ? (
                    <div className="chat_logo_circle"></div>
                  ) : (
                    <div className="chat_logo_circle_empty"></div>
                  )}
                  {/* Only show response if not thinking */}
                  <div className="response_main_container">
                    <div
                      className={`assistant_with_dropdown_container ${
                        chat.thinkingResponse ? "" : "dis_none"
                      } ${
                        showThinkingResponseContent.includes(idx)
                          ? "thinking_response_container"
                          : ""
                      }`}
                      onClick={() => handleThinkingResponseClick(idx)}
                      tabIndex={0}
                      onKeyDown={(e) => {
                        if (e.key === "Enter" || e.key === " ") {
                          handleThinkingResponseClick(idx);
                        }
                      }}
                    >
                      {chat?.thinkingResponse?.thinkingHeading}
                    </div>
                    <div
                      className={`thinking_response_content ${
                        showThinkingResponseContent.includes(idx)
                          ? "show-thinking-response-content"
                          : ""
                      } ${chat.thinkingResponse ? "" : "dis_none"}`}
                    >
                      {chat?.thinkingResponse?.thinkingContent}
                    </div>
                    <div
                      className={`assistant_main_container ${
                        chat.bodyType === "questions"
                          ? "questions-container"
                          : ""
                      }`}
                    >
                      <div className={`assistant_text_container`}>
                        {chat.type === "jsx" && chat.jsx}
                        {chat.type === "form" && chat.formComponent}
                        {chat.type === "table" && chat.tableComponent}
                        {chat.type === "text" && chat.text}
                      </div>
                      <div className="time_chat">
                        {chat.timestamp
                          ? formatAMPM(new Date(chat.timestamp))
                          : ""}
                      </div>
                    </div>
                    <div className="assistant_actions_container">
                      <div className="left_icon_container_action">
                        <button
                          className={`asst_feedback_buttons good_feedback ${
                            chat?.enableLikes ? "" : "dis_none"
                          } ${chat?.extra?.status === "liked" ? "liked" : ""} ${
                            chat.isAnimateLike ? "animatingLike" : ""
                          }`}
                          onClick={() => handleLikeClick(chat, idx)}
                        ></button>
                        <button
                          className={`asst_feedback_buttons bad_feedback ${
                            chat?.enableLikes ? "" : "dis_none"
                          } ${
                            chat?.extra?.status === "disliked" ? "disliked" : ""
                          } ${chat.isAnimateDislike ? "animatingDislike" : ""}`}
                          onClick={() => handleDislikeClick(chat, idx)}
                        ></button>
                        <button
                          className={`asst_feedback_buttons speaker ${
                            chat?.enableSpeaker ? "" : "dis_none"
                          }`}
                        ></button>
                      </div>
                      <div className="button_url_container">
                        <button
                          className={`asst_feedback_buttons ${
                            chat?.enableNewThread ? "" : "dis_none"
                          }`}
                        >
                          New Thread
                        </button>
                      </div>
                      <div className="button_url_container">
                        <button
                          className={`asst_feedback_buttons ${
                            chat?.enableAddToPage ? "" : "dis_none"
                          }`}
                        >
                          Add to Page
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
              ) : null}
            </React.Fragment>
          );
        })}
        {isAssistantThinking && (
          <div className="assistant_chat_messages_container">
            <div className="chat_logo_circle"></div>
            <div
              className={`loading_messages ${
                isAssistantThinking ? "" : "dis_none"
              }`}
            >
              <span className="dot"></span>
              <span className="dot"></span>
              <span className="dot"></span>
            </div>
          </div>
        )}

        {/* Assistant chat ends here  */}
      </div>

      {/* Conversation body ends here  */}

      {/* Conversation footer starts here  */}

      <div className="conversation-footer-container">
        <ChatInput
          inputValue={input}
          setInputValue={setInput}
          minRows={1}
          userChats={userChats}
          setUserChats={setUserChats}
          onSendIconClick={onSendIconClick}
          activeList={activeList}
          handleRefresh={handleRefresh}
          handleSaveChat={handleSaveChat}
          handleMicClick={handleMicClick}
          suggestionBanner={suggestionBanner}
          isStopIcon={isStopIcon}
          onStopIconClick={onStopIconClick}
          onCloseSuggestionBanner={onCloseSuggestionBanner}
          showSuggestionBanner={showSuggestionBanner}
          customInputComponent={customInputComponent}
        />
      </div>

      {/* Conversation footer ends here  */}
    </div>
  );
};
