import React, { useEffect, useRef, useState } from "react";
import {
  AsileIcon,
  CommentIcon,
  CursorIcon,
  FloorIcon,
  FreeMoveIcon,
  PenIcon,
  PlayIcon,
  SaveTemplateIcon,
  WallIcon,
  ZoneIcon,
} from "../icons/ExportToolsIcons";
import { ArrowIcon, TickIcon } from "../icons/ExportCommonIcons";
import useModuleStore from "../../store/useModuleStore";
import { handleSaveTemplate } from "../../modules/visualization/handleSaveTemplate";
import { usePlayButtonStore } from "../../store/usePlayButtonStore";
import useTemplateStore from "../../store/useTemplateStore";
import { useSelectedZoneStore } from "../../store/useZoneStore";

const Tools: React.FC = () => {
  const { templates } = useTemplateStore();
  const [activeTool, setActiveTool] = useState("cursor");
  const [activeSubTool, setActiveSubTool] = useState("cursor");
  const [toggleThreeD, setToggleThreeD] = useState(true);

  const dropdownRef = useRef<HTMLDivElement>(null);
  const [openDrop, setOpenDrop] = useState(false);

  const { activeModule } = useModuleStore();
  const { isPlaying, setIsPlaying } = usePlayButtonStore();
  const { addTemplate } = useTemplateStore();
  const { selectedZone } = useSelectedZoneStore();

  // Reset activeTool whenever activeModule changes
  useEffect(() => {
    setActiveTool(activeSubTool);
    setActiveSubTool(activeSubTool);
  }, [activeModule]);

  useEffect(() => {
    const handleOutsideClick = (event: MouseEvent) => {
      if (
        dropdownRef.current &&
        !dropdownRef.current.contains(event.target as Node)
      ) {
        setOpenDrop(false); // Close the dropdown
      }
    };

    document.addEventListener("mousedown", handleOutsideClick);

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

  return (
    <div className="tools-container">
      <div className="drop-down-icons">
        <div className="activeDropicon">
          {activeSubTool == "cursor" && (
            <div
              className={`tool-button ${
                activeTool === "cursor" ? "active" : ""
              }`}
              onClick={() => {
                setActiveTool("cursor");
              }}
            >
              <CursorIcon isActive={activeTool === "cursor"} />
            </div>
          )}
          {activeSubTool == "free-hand" && (
            <div
              className={`tool-button ${
                activeTool === "free-hand" ? "active" : ""
              }`}
              onClick={() => {
                setActiveTool("free-hand");
              }}
            >
              <FreeMoveIcon isActive={activeTool === "free-hand"} />
            </div>
          )}
          {activeModule !== "visualization" && (
            <div
              className="drop-down-option-button"
              ref={dropdownRef}
              onClick={() => {
                setOpenDrop(!openDrop);
                console.log(openDrop);
              }}
            >
              <ArrowIcon />
              {openDrop && (
                <div className="drop-down-container">
                  <div
                    className="option-list"
                    onClick={() => {
                      setOpenDrop(false);
                      setActiveTool("cursor");
                      setActiveSubTool("cursor");
                    }}
                  >
                    <div className="active-option">
                      {activeSubTool === "cursor" && <TickIcon />}
                    </div>
                    <CursorIcon isActive={false} />
                    <div className="option">Cursor</div>
                  </div>
                  <div
                    className="option-list"
                    onClick={() => {
                      setOpenDrop(false);
                      setActiveTool("free-hand");
                      setActiveSubTool("free-hand");
                    }}
                  >
                    <div className="active-option">
                      {activeSubTool === "free-hand" && <TickIcon />}
                    </div>
                    <FreeMoveIcon isActive={false} />
                    <div className="option">Free Hand</div>
                  </div>
                </div>
              )}
            </div>
          )}
        </div>
      </div>
      {!toggleThreeD && activeModule === "builder" && (
        <>
          <div className="split"></div>
          <div className="draw-tools">
            <div
              className={`tool-button ${
                activeTool === "draw-wall" ? "active" : ""
              }`}
              onClick={() => {
                setActiveTool("draw-wall");
              }}
            >
              <WallIcon isActive={activeTool === "draw-wall"} />
            </div>
            <div
              className={`tool-button ${
                activeTool === "draw-zone" ? "active" : ""
              }`}
              onClick={() => {
                setActiveTool("draw-zone");
              }}
            >
              <ZoneIcon isActive={activeTool === "draw-zone"} />
            </div>
            <div
              className={`tool-button ${
                activeTool === "draw-aisle" ? "active" : ""
              }`}
              onClick={() => {
                setActiveTool("draw-aisle");
              }}
            >
              <AsileIcon isActive={activeTool === "draw-aisle"} />
            </div>
            <div
              className={`tool-button ${
                activeTool === "draw-floor" ? "active" : ""
              }`}
              onClick={() => {
                setActiveTool("draw-floor");
              }}
            >
              <FloorIcon isActive={activeTool === "draw-floor"} />
            </div>
          </div>
        </>
      )}
      {activeModule === "simulation" && (
        <>
          <div className="split"></div>
          <div className="draw-tools">
            <div
              className={`tool-button ${activeTool === "pen" ? "active" : ""}`}
              onClick={() => {
                setActiveTool("pen");
              }}
            >
              <PenIcon isActive={activeTool === "pen"} />
            </div>
          </div>
        </>
      )}
      {activeModule === "visualization" && (
        <>
          <div className="split"></div>
          <div className="draw-tools">
            <div
              className={`tool-button`}
              onClick={() =>
                handleSaveTemplate({
                  addTemplate,
                  selectedZone,
                  templates,
                })
              }
            >
              <SaveTemplateIcon isActive={false} />
            </div>
          </div>
        </>
      )}
      <div className="split"></div>
      <div className="general-options">
        <div
          className={`tool-button ${activeTool === "comment" ? "active" : ""}`}
          onClick={() => {
            setActiveTool("comment");
          }}
        >
          <CommentIcon isActive={activeTool === "comment"} />
        </div>
        <div
          className={`tool-button ${activeTool === "play" ? "active" : ""}`}
          onClick={() => {
            setActiveTool("play");
            setIsPlaying(!isPlaying);
          }}
        >
          <PlayIcon isActive={activeTool === "play"} />
        </div>
      </div>
      <div className="split"></div>
      <div
        className={`toggle-threed-button${toggleThreeD ? " toggled" : ""}`}
        onClick={() => {
          setToggleThreeD(!toggleThreeD);
        }}
      >
        <div className={`toggle-option${!toggleThreeD ? " active" : ""}`}>
          2d
        </div>
        <div className={`toggle-option${toggleThreeD ? " active" : ""}`}>
          3d
        </div>
      </div>
    </div>
  );
};

export default Tools;
