import React, { useState, useEffect } from "react";
import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown";
import KeyboardArrowUpIcon from "@mui/icons-material/KeyboardArrowUp";
import SmartBotIcon from "../../assets/smartBotAlan.svg";
import { Button } from "../Button";
import ActiveIcon from "../../assets/activeModuleIcon.svg";
import CloseThreadIcon from "../../assets/close.svg";
import SaveOutlinedIcon from "@mui/icons-material/SaveOutlined";
import RemoveRoundedIcon from "@mui/icons-material/RemoveRounded";
import HomeIcon from "../../assets/chat-home-icon.svg";
import { Loader } from "../Loader";
import ClearIcon from "@mui/icons-material/Clear";

export const ChatbotModuleMenu = ({
  hideMenuArrow,
  onModuleClick,
  moduleList,
  activeList,
  hideChildren = false,
  isModuleListLoading,
  hideSmartBotIcon = false,
  hideCenterOptions = false,
  threadList: threadListProp,
  activeThread: activeThreadProp,
  handleSavedChat,
  onClose,
  isFullWidth,
  onMinimiseChatBot,
}) => {
  const [isDropdownOpen, setIsDropdownOpen] = useState(false);
  const [activeModule, setActiveModule] = useState(
    moduleList.find((module) => module.isActive)?.name || ""
  );
  const [threadList, setThreadList] = useState(threadListProp);
  const [activeThread, setActiveThread] = useState(
    activeThreadProp || threadListProp[0]
  );

  const handleCloseThread = (e, idx) => {
    e.stopPropagation();
    e.preventDefault();
    const newThreadList = [...threadList];
    newThreadList.splice(idx, 1);
    setThreadList(newThreadList);
  };

  const handleClickOutside = (e) => {
    if (!e.target.closest(".chatbot-component-header-dropdown-container")) {
      setIsDropdownOpen(false);
    }
  };

  useEffect(() => {
    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, []);

  return (
    <div className="conversation-screen-container-header">
      {/* left logo and arrow starts here  */}

      <div className="left_logo_arrow_container">
        {!hideSmartBotIcon && (
          <div className="conversation_chatbot_logo_container">
            <img src={SmartBotIcon} />
          </div>
        )}
        {!hideMenuArrow && (
          <div className="menu_arrow">
            <Button
              icon={
                isDropdownOpen ? (
                  <KeyboardArrowUpIcon />
                ) : (
                  <KeyboardArrowDownIcon />
                )
              }
              iconPlacement="right"
              size={hideChildren ? "small" : "medium"}
              type="default"
              variant="text"
              onClick={() => {
                setIsDropdownOpen(!isDropdownOpen);
              }}
            >
              {!hideChildren && "Module"}
            </Button>
            {isDropdownOpen && (
              <div
                className={`chatbot-component-header-dropdown-container ${isDropdownOpen ? "open" : ""
                  }`}
                style={{
                  width: 397,
                  position: "absolute",
                  boxShadow: "0px 1px 6px 0px #1933451A",
                  top: 52,
                  zIndex: 999999,
                  backgroundColor: "white",
                  padding: "16px",
                  borderRadius: "18px",
                }}
              >
                {isModuleListLoading ? (
                  <Loader />
                ) : (
                  <div
                    className="chatbot-component-header-dropdown-item"
                    key={module.id}
                    style={{
                      display: "flex",
                      flexDirection: "column",
                      justifyContent: "center",
                      backgroundColor: "white",
                      gap: 16,
                      cursor: "pointer",
                    }}
                  >
                    {moduleList.map((module) => (
                      <div
                        onClick={() => {
                          setActiveModule(module.name);
                          onModuleClick(module.id, module.name, activeList);
                          setIsDropdownOpen(false);
                        }}
                        className="chatbot-component-header-dropdown-item-container"
                        style={{
                          display: "flex",
                          height: 66,
                          alignItems: "center",
                          justifyContent: "space-between",
                          padding: "12px",
                        }}
                      >
                        <div
                          style={{
                            display: "flex",
                            alignItems: "center",
                            gap: 10,
                          }}
                          className="chatbot-component-header-dropdown-item-content"
                        >
                          {typeof module.icon === "string" ? (
                            <img src={module.icon} alt={module.key} />
                          ) : (
                            module.icon
                          )}
                          <div
                            style={{ display: "flex", flexDirection: "column" }}
                            className="chatbot-component-header-dropdown-item-content-text"
                          >
                            <span
                              className="chatbot-component-header-dropdown-item-content-text-name"
                              style={{
                                fontWeight: 600,
                                fontSize: 16,
                                lineHeight: "24px",
                                color: "#1F2B4D",
                              }}
                            >
                              {module.name}
                            </span>
                            <span
                              className="chatbot-component-header-dropdown-item-content-text-description"
                              style={{
                                fontWeight: 500,
                                fontSize: 12,
                                lineHeight: "16px",
                                color: "#7A8294",
                              }}
                            >
                              {module.description}
                            </span>
                          </div>
                        </div>
                        {activeModule === module.name && (
                          <img src={ActiveIcon} />
                        )}
                      </div>
                    ))}
                  </div>
                )}
              </div>
            )}
          </div>
        )}
      </div>

      {/* left logo and arrow ends here  */}

      {/* Center options stars here  */}

      {!hideCenterOptions && (
        <div className="center_options_container">
          <div className="left_tabs_container">
            <ul>
              {threadList.map((thread, idx) => (
                <li
                  key={idx}
                  role="tab"
                  tabIndex={0}
                  className={`${activeThread === thread ? "active" : ""} ${thread === "Home" ? "home" : ""
                    }`}
                  onClick={() => {
                    setActiveThread(thread);
                    handleThreadClick?.(thread);
                  }}
                  onKeyDown={(e) => {
                    if (e.key === "Enter" || e.key === " ") {
                      e.preventDefault();
                      setActiveThread(thread);
                      handleThreadClick?.(thread);
                    }
                  }}
                >
                  <>
                    {thread === "Home" ? (
                      <img src={HomeIcon} alt="Home" />
                    ) : (
                      <>
                        {thread}
                        <span
                          className="close_thread"
                          role="button"
                          tabIndex={0}
                          onKeyDown={(e) => {
                            if (e.key === "Enter" || e.key === " ") {
                              e.preventDefault();
                              e.stopPropagation();
                              handleCloseThread(e, idx);
                            }
                          }}
                        >
                          <img
                            src={CloseThreadIcon}
                            alt="Close thread"
                            onClick={(e) => handleCloseThread(e, idx)}
                          />
                        </span>
                      </>
                    )}
                  </>
                </li>
              ))}
            </ul>
          </div>
          <div className="right_info_container"></div>
        </div>
      )}

      {/* Center options ends here  */}

      {/* Right close save icon starts here  */}

      <div className="right_close_save_icon_container">
        {onMinimiseChatBot && !isFullWidth && (
          <div className="minimise_icon_container">
            <Button
              className="chatbot-component-header-close-icon"
              icon={<RemoveRoundedIcon />}
              size="small"
              type="default"
              variant="text"
              onClick={onMinimiseChatBot}
            />
          </div>
        )}

        {handleSavedChat && (
          <div className="save_icon_container">
            <Button
              icon={<SaveOutlinedIcon />}
              iconPlacement="left"
              size="small"
              type="default"
              variant="text"
              onClick={handleSavedChat}
            />
          </div>
        )}

        {!isFullWidth && (
          <div className="close_icon_container">
            <Button
              icon={<ClearIcon />}
              iconPlacement="left"
              size="small"
              type="default"
              variant="text"
              onClick={onClose}
            />
          </div>
        )}
      </div>

      {/* Right close icon ends here  */}
    </div>
  );
};
