import React, { useState, useEffect, useMemo } from "react";
import "./chatBot.style.scss";
import { ChatBotFooter } from "./chatBotFooter";
import { NewChatComponent } from "./newChatComponent";
import { ConversationScreen } from "./conversationScreen";
import ChatBotLandingScreen from "./chatBotLandingScreen";
import { menuItems as defaultMenuItems, mandatoryTabList } from "./constant";
import { BookMarkPanel } from "./bookMarkPanel";
import { HistoryPanel } from "./historyPanel";
import BookMarkIcon from "../../assets/bookmarkIcon.svg";
import NewChatIcon from "../../assets/newChatIcon.svg";
import { CustomScreen } from "./customScreen";
import { Tooltip } from "../Tooltip";
import { ChatbotModuleMenu } from "./chatbotModuleMenu";
export const ChatBotComponent = ({
  onClose,
  userName,
  isChatBotOpen,
  setIsChatBotOpen,
  conversation = [],
  solution,
  formComponent,
  tableComponent,
  preDefinedQuestions,
  addedByYouQuestions,
  onSendIconClick = () => {},
  assistantChats = [],
  isAssistantThinking = false,
  moduleList = [],
  onModuleClick = () => {},
  tabList,
  handleSavedChat,
  threadList = ["Home", "Thread 1", "Thread 2"],
  activeThread = null,
  isCustomScreen = false,
  customScreenJsx = null,
  onLikeClick = () => {},
  onDislikeClick = () => {},
  handleNewChatClick = () => {},
  inputText = "",
  handleRefresh,
  handleSaveChat,
  handleMicClick,
  hideMenuArrow = false,
  newChatScreen = false,
  isModuleListLoading = false,
  suggestionBanner = {
    freeTextHeading: "Try adding more details:",
    freeTextContent:
      "Alan works best when your input has context and pointed questions",
  },
  isStopIcon = false,
  onStopIconClick = () => {},
  landingScreen = false,
  footerText = "AI-generated responses may contain errors—please verify important information",
  onCloseSuggestionBanner = () => {},
  showSuggestionBanner = false,
  utilityList = [],
  customInputComponent = null,
  onHistoryPanelClick = () => {},
  historyPanelData = [],
  onHistorySearchChange = () => {},
  onHistorySelectConversation = () => {},
  onHistoryToggleGroup = () => {},
  historyOpenGroups,
  onHistoryMenuAction = () => {},
  showHistoryPanel = true,
  isFullWidth = false,
  activeConversationId,
  handleCloseThread = () => {},
  handleThreadClick = () => {},
  onMinimiseChatBot,
  onChatBotResize = () => {},
}) => {
  const [isNewChat, setIsNewChat] = useState(
    tabList?.find((tab) => tab.isActive) ? false : newChatScreen ? true : false
  );
  const [inputValue, setInputValue] = useState(inputText);
  const [containerWidth, setContainerWidth] = useState(
    isFullWidth ? `calc(100vw - 64px)` : "690px"
  );
  const [question, setQuestion] = useState(conversation || []);
  const [answer, setAnswer] = useState(solution);
  const [activeList, setActiveList] = useState(
    tabList?.find((tab) => tab?.initialClick)?.name
  );
  const [isBookMarkPanelOpen, setIsBookMarkPanelOpen] = useState(false);
  const [isHistoryPanelOpen, setIsHistoryPanelOpen] = useState(false);
  const [isPagePanelOpen, setIsPagePanelOpen] = useState(false);
  const [isNotificationPanelOpen, setIsNotificationPanelOpen] = useState(false);
  const [userChats, setUserChats] = useState([]);
  const [menuItems, setMenuItems] = useState([]);
  const [localHistoryOpenGroups, setLocalHistoryOpenGroups] = useState({});
  const panelsOpen = useMemo(() => {
    return isBookMarkPanelOpen || isHistoryPanelOpen || isPagePanelOpen;
  }, [isBookMarkPanelOpen, isHistoryPanelOpen, isPagePanelOpen]);

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

  useEffect(() => {
    const newChatItem = {
      key: "newchat",
      icon: NewChatIcon,
      className: "chatbot-component-menu-container-icon-new-chat",
    };
    if (tabList && Array.isArray(tabList)) {
      setMenuItems([
        newChatItem,
        ...tabList?.map((tab, idx) => ({
          ...tab,
          key: tab.name?.toLowerCase() || `tab${idx}`,
          icon: tab.icon || BookMarkIcon,
          className: `chatbot-component-menu-container-icon-${tab.name?.toLowerCase()}`,
          label: tab.name,
          onClick: tab.onClick,
        })),
        ...(showHistoryPanel ? mandatoryTabList : []),
      ]);
    } else {
      setMenuItems([newChatItem, ...defaultMenuItems]);
    }
  }, [tabList]);

  useEffect(() => {
    if (isChatBotOpen) {
      const resizer = document.querySelector(".resizer");
      let startX, startWidth;

      const onMouseMove = (e) => {
        const dx = e.clientX - startX;
        let newWidth = startWidth - dx;
        const minAllowed = panelsOpen ? 690 + 360 : 690;
        const maxAllowed = window.innerWidth - 100;
        if (newWidth <= minAllowed) newWidth = minAllowed;
        if (newWidth > maxAllowed) newWidth = maxAllowed;
        setContainerWidth(`${newWidth}px`);
        onChatBotResize?.(newWidth);
      };

      const onMouseUp = () => {
        document.body.classList.remove("no-select");
        document.removeEventListener("mousemove", onMouseMove);
        document.removeEventListener("mouseup", onMouseUp);
      };

      const onMouseDown = (e) => {
        startX = e.clientX;
        startWidth = document
          .querySelector(".chatbot-component-container")
          .getBoundingClientRect().width;
        document.body.classList.add("no-select");
        document.addEventListener("mousemove", onMouseMove);
        document.addEventListener("mouseup", onMouseUp);
      };
      setActiveList(tabList?.find((tab) => tab?.initialClick)?.name);
      menuItems
        ?.find((tab) => tab?.initialClick)
        ?.onClick(menuItems?.find((tab) => tab?.initialClick));
      if (resizer && !isFullWidth) {
        resizer.addEventListener("mousedown", onMouseDown);
      } else if (isFullWidth) {
        setContainerWidth(`calc(100vw - 64px)`);
      }

      return () => {
        resizer?.removeEventListener("mousedown", onMouseDown);
      };
    }
  }, [isChatBotOpen, panelsOpen, isFullWidth]);

  const handleCloseChatBot = () => {
    setIsChatBotOpen(false);
    setIsHistoryPanelOpen(false);
    setIsBookMarkPanelOpen(false);
    setIsPagePanelOpen(false);
    onClose?.();
  };

  const handleMenuClick = (item) => {
    if (item?.key === "newchat") {
      setInputValue("");
      let tabDetails = handleNewChatClick?.(item);
      if (tabDetails?.isInitialClickPresent) {
        let initialClickItem = tabList.find(
          (item) =>
            item?.name?.toLowerCase() === tabDetails?.tabName?.toLowerCase()
        );
        initialClickItem?.onClick?.(initialClickItem);
      }
      setActiveList(
        tabList.find(
          (item) =>
            item?.name?.toLowerCase() === tabDetails?.tabName?.toLowerCase()
        )?.name
      );
    } else if (item?.key === "history") {
      setIsHistoryPanelOpen(!isHistoryPanelOpen);
      onHistoryPanelClick?.(item, !isHistoryPanelOpen);
    } else {
      setActiveList(item?.key);
      item?.onClick?.(item);
    }
  };

  const handleCloseLeftPanel = () => {
    setIsBookMarkPanelOpen(false);
    setIsHistoryPanelOpen(false);
    setIsPagePanelOpen(false);
  };

  useEffect(() => {
    if (panelsOpen) {
      setContainerWidth((prev) => {
        return Math.min(parseInt(prev) + 360, window.innerWidth - 100);
      });
    } else {
      setContainerWidth((prev) => {
        return Math.max(parseInt(prev) - 360, 690);
      });
    }
  }, [panelsOpen]);

  return (
    <>
      {isChatBotOpen ? (
        <div className="chatbot-modal-wrapper">
          <div className="resizer" />
          <div
            className="chatbot-component-container"
            style={{ width: containerWidth }}
          >
            {landingScreen ? (
              <ChatBotLandingScreen
                onClose={handleCloseChatBot}
                isFullWidth={isFullWidth}
              />
            ) : (
              <>
                <div
                  className={`chatbot-component-left-side ${
                    isBookMarkPanelOpen || isHistoryPanelOpen || isPagePanelOpen
                      ? "chatbot-component-left-side-open"
                      : ""
                  }`}
                >
                  <div
                    className={`chatbot-component-menu-container ${
                      isBookMarkPanelOpen ||
                      isHistoryPanelOpen ||
                      isPagePanelOpen
                        ? "chatbot-component-menu-container-open"
                        : ""
                    }`}
                  >
                    <div
                      className={`chatbot-component-menu-container-icon ${
                        isBookMarkPanelOpen ||
                        isHistoryPanelOpen ||
                        isPagePanelOpen
                          ? "chatbot-component-menu-container-icon-open"
                          : ""
                      }`}
                    >
                      <ul className="chatbot-component-menu-list">
                        {menuItems?.map((item) => (
                          <Tooltip
                            title={
                              item.key.charAt(0).toUpperCase() +
                              item.key.slice(1)
                            }
                            variant="tertiary"
                            orientation="left"
                          >
                            <li
                              key={item.key}
                              role="button"
                              tabIndex={0}
                              className={`${item.className} ${
                                activeList?.toLowerCase() ===
                                item?.key?.toLowerCase()
                                  ? "active"
                                  : ""
                              }`}
                              onClick={() => handleMenuClick(item)}
                              onKeyDown={(e) => {
                                if (e.key === "Enter" || e.key === " ") {
                                  e.preventDefault();
                                  handleMenuClick(item);
                                }
                              }}
                            >
                              {typeof item.icon === "string" ? (
                                <img
                                  src={item.icon}
                                  className={item.iconClassName}
                                  alt={item.key}
                                />
                              ) : (
                                item.icon
                              )}
                            </li>
                          </Tooltip>
                        ))}
                      </ul>
                      <ul className="chatbot-component-menu-list utility-list">
                        {utilityList?.map((item) => (
                          <Tooltip
                            title={
                              item.key.charAt(0).toUpperCase() +
                              item.key.slice(1)
                            }
                            variant="tertiary"
                            orientation="left"
                          >
                            <li
                              key={item.key}
                              role="button"
                              tabIndex={0}
                              onClick={item.onClick}
                              onKeyDown={(e) => {
                                if (e.key === "Enter" || e.key === " ") {
                                  e.preventDefault();
                                  item.onClick?.();
                                }
                              }}
                            >
                              {typeof item.icon === "string" ? (
                                <img src={item.icon} alt={item.key} />
                              ) : (
                                item.icon
                              )}
                            </li>
                          </Tooltip>
                        ))}
                      </ul>
                    </div>
                    {isBookMarkPanelOpen &&
                      !isHistoryPanelOpen &&
                      !isPagePanelOpen && (
                        <BookMarkPanel
                          preDefinedQuestions={preDefinedQuestions}
                          addedByYouQuestions={addedByYouQuestions}
                          onClose={handleCloseLeftPanel}
                        />
                      )}
                    {isHistoryPanelOpen &&
                      !isBookMarkPanelOpen &&
                      !isPagePanelOpen && (
                        <HistoryPanel
                          historyPanelData={historyPanelData}
                          onClose={handleCloseLeftPanel}
                          onSearchChange={onHistorySearchChange}
                          onSelectConversation={onHistorySelectConversation}
                          onToggleGroup={(groupName, isOpen) => {
                            if (historyOpenGroups == null) {
                              setLocalHistoryOpenGroups((prev) => ({
                                ...prev,
                                [groupName]: isOpen,
                              }));
                            }
                            onHistoryToggleGroup?.(groupName, isOpen);
                          }}
                          openGroups={
                            historyOpenGroups ?? localHistoryOpenGroups
                          }
                          onMenuAction={onHistoryMenuAction}
                          activeConversationId={activeConversationId}
                        />
                      )}
                  </div>
                </div>
                <div
                  className={`chatbot-component-right-side ${
                    isBookMarkPanelOpen || isHistoryPanelOpen || isPagePanelOpen
                      ? "chatbot-component-right-side-open"
                      : ""
                  }`}
                >
                  {!isCustomScreen && (
                    <div className="conversation-screen-container">
                      <ChatbotModuleMenu
                        hideMenuArrow={hideMenuArrow}
                        moduleList={moduleList}
                        activeList={activeList}
                        onModuleClick={onModuleClick}
                        hideChildren={!newChatScreen}
                        isModuleListLoading={isModuleListLoading}
                        hideCenterOptions={newChatScreen}
                        threadList={threadList}
                        activeThread={activeThread}
                        handleSavedChat={handleSavedChat}
                        onClose={handleCloseChatBot}
                        isFullWidth={isFullWidth}
                        handleCloseThread={handleCloseThread}
                        handleThreadClick={handleThreadClick}
                        onMinimiseChatBot={onMinimiseChatBot}
                      />
                    </div>
                  )}
                  {newChatScreen ? (
                    <NewChatComponent
                      onClose={handleCloseChatBot}
                      userName={userName}
                      inputValue={inputValue}
                      setInputValue={setInputValue}
                      setIsNewChat={setIsNewChat}
                      onSendIconClick={onSendIconClick}
                      userChats={userChats}
                      setUserChats={setUserChats}
                      moduleList={moduleList}
                      onModuleClick={onModuleClick}
                      activeList={activeList}
                      handleRefresh={handleRefresh}
                      handleSaveChat={handleSaveChat}
                      handleMicClick={handleMicClick}
                      hideMenuArrow={hideMenuArrow}
                      isModuleListLoading={isModuleListLoading}
                      suggestionBanner={suggestionBanner}
                      isStopIcon={isStopIcon}
                      onStopIconClick={onStopIconClick}
                      onCloseSuggestionBanner={onCloseSuggestionBanner}
                      showSuggestionBanner={showSuggestionBanner}
                      customInputComponent={customInputComponent}
                    />
                  ) : isCustomScreen ? (
                    <CustomScreen
                      onClose={handleCloseChatBot}
                      customScreenJsx={customScreenJsx}
                      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}
                      isFullWidth={isFullWidth}
                      onMinimiseChatBot={onMinimiseChatBot}
                    />
                  ) : (
                    <ConversationScreen
                      conversation={conversation}
                      setConversation={setQuestion}
                      solution={answer}
                      inputValue={inputValue}
                      onClose={handleCloseChatBot}
                      formComponent={formComponent}
                      tableComponent={tableComponent}
                      containerWidth={containerWidth}
                      userChats={userChats}
                      setUserChats={setUserChats}
                      assistantChats={assistantChats}
                      onSendIconClick={onSendIconClick}
                      isAssistantThinking={isAssistantThinking}
                      moduleList={moduleList}
                      onModuleClick={onModuleClick}
                      activeList={activeList}
                      handleSavedChat={handleSavedChat}
                      threadList={threadList}
                      activeThread={activeThread}
                      onLikeClick={onLikeClick}
                      onDislikeClick={onDislikeClick}
                      inputText={inputText}
                      handleRefresh={handleRefresh}
                      handleSaveChat={handleSaveChat}
                      handleMicClick={handleMicClick}
                      hideMenuArrow={hideMenuArrow}
                      isModuleListLoading={isModuleListLoading}
                      suggestionBanner={suggestionBanner}
                      isStopIcon={isStopIcon}
                      onStopIconClick={onStopIconClick}
                      onCloseSuggestionBanner={onCloseSuggestionBanner}
                      showSuggestionBanner={showSuggestionBanner}
                      customInputComponent={customInputComponent}
                    />
                  )}
                  <ChatBotFooter footerText={footerText} />
                </div>
              </>
            )}
          </div>
        </div>
      ) : null}
    </>
  );
};
