import React, { useEffect, useRef, useState } from "react";
import {
  AsileIcon,
  CommentIcon,
  CursorIcon,
  DeleteIcon,
  FloorIcon,
  FreeMoveIcon,
  MeasureToolIcon,
  PenIcon,
  PlayIcon,
  SaveTemplateIcon,
  WallIcon,
  ZoneIcon,
} from "../icons/ExportToolsIcons";
import { ArrowIcon, TickIcon } from "../icons/ExportCommonIcons";
import useModuleStore, { useThreeDStore } from "../../store/useModuleStore";
import { handleSaveTemplate } from "../../modules/visualization/functions/handleSaveTemplate";
import { usePlayButtonStore } from "../../store/usePlayButtonStore";
import useTemplateStore from "../../store/useTemplateStore";
import { useSelectedZoneStore } from "../../store/visualization/useZoneStore";
import {
  useActiveTool,
  useAddAction,
  useDeleteTool,
  useDeletePointOrLine,
  useMovePoint,
  useRefTextUpdate,
  useSelectedWallItem,
  useSocketStore,
  useToggleView,
  useToolMode,
  useTransformMode,
  useActiveSubTool,
} from "../../store/store";
import useToggleStore from "../../store/useUIToggleStore";
import {
  use3DWidget,
  useFloatingWidget,
} from "../../store/visualization/useDroppedObjectsStore";

const Tools: React.FC = () => {
  const { templates } = useTemplateStore();
  const { activeSubTool, setActiveSubTool } = useActiveSubTool();
  const { toggleThreeD, setToggleThreeD } = useThreeDStore();
  const { setToggleUI } = useToggleStore();

  const dropdownRef = useRef<HTMLDivElement>(null);
  const [openDrop, setOpenDrop] = useState(false);
  const { visualizationSocket } = useSocketStore();
  const { activeModule } = useModuleStore();
  const { isPlaying, setIsPlaying } = usePlayButtonStore();
  const { addTemplate } = useTemplateStore();
  const { selectedZone } = useSelectedZoneStore();
  const { floatingWidget } = useFloatingWidget();

  const { widgets3D } = use3DWidget();

  // wall options
  const { toggleView, setToggleView } = useToggleView();
  const { setDeleteTool } = useDeleteTool();
  const { setAddAction } = useAddAction();
  const { setSelectedWallItem } = useSelectedWallItem();

  const { setTransformMode } = useTransformMode();
  const { setDeletePointOrLine } = useDeletePointOrLine();
  const { setMovePoint } = useMovePoint();
  const { setToolMode } = useToolMode();
  const { activeTool, setActiveTool } = useActiveTool();
  const { setRefTextUpdate } = useRefTextUpdate();

  // Reset activeTool whenever activeModule changes
  useEffect(() => {
    setToggleUI(
      localStorage.getItem("navBarUi")
        ? localStorage.getItem("navBarUi") === "true"
        : true
    );
  }, []);
  useEffect(() => {}, [activeModule]);
  useEffect(() => {
    setActiveTool(activeSubTool);
    setActiveSubTool(activeSubTool);
  }, [activeModule]);

  const toggleSwitch = () => {
    if (toggleThreeD) {
      setSelectedWallItem(null);
      setDeleteTool(false);
      setAddAction(null);
      setToggleView(true);
      // localStorage.setItem("navBarUi", JSON.stringify(!toggleThreeD));
    } else {
      setToggleView(false);
    }
    setToggleUI(
      localStorage.getItem("navBarUi")
        ? localStorage.getItem("navBarUi") === "true"
        : true
    );
    setToggleThreeD(!toggleThreeD);
    setActiveSubTool("cursor");
    setActiveTool("cursor");
  };

  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);
    };
  }, []);
  useEffect(() => {
    if (!toggleThreeD) {
      setToggleUI(false);
    }
  }, [toggleThreeD]);

  useEffect(() => {
    setToolMode(null);
    setDeleteTool(false);
    setAddAction(null);
    setTransformMode(null);
    setMovePoint(false);
    setDeletePointOrLine(false);
    setRefTextUpdate((prevUpdate) => prevUpdate - 1);

    switch (activeTool) {
      case "Move":
        if (toggleView) {
          setMovePoint(true);
        } else {
          setTransformMode("translate");
        }
        break;

      case "Rotate":
        if (!toggleView) {
          setTransformMode("rotate");
        }
        break;

      case "Scale":
        if (!toggleView) {
          setTransformMode("scale");
        }
        break;

      case "draw-wall":
        if (toggleView) {
          setToolMode("Wall");
        }
        break;

      case "draw-aisle":
        if (toggleView) {
          setToolMode("Aisle");
        }
        break;

      case "draw-zone":
        if (toggleView) {
          setToolMode("Zone");
        }
        break;

      case "draw-floor":
        if (toggleView) {
          setToolMode("Floor");
        }
        break;

      case "measure":
        setToolMode("MeasurementScale");
        break;

      case "Add pillar":
        if (!toggleView) {
          setAddAction("pillar");
        }
        break;

      case "delete":
        if (toggleView) {
          setDeletePointOrLine(true);
        } else {
          setDeleteTool(true);
        }
        break;

      default:
        break;
    }

    setActiveTool(activeTool);
  }, [activeTool]);

  return (
    <>
      {!isPlaying ? (
        <div className="tools-container">
          <div className="drop-down-icons">
            <div className="activeDropicon">
              {activeSubTool == "cursor" && (
                <div
                  className={`tool-button ${
                    activeTool === "cursor" ? "active" : ""
                  }`}
                  onClick={() => {
                    setActiveTool("cursor");
                  }}
                >
                  <div className="tooltip">cursor (v)</div>
                  <CursorIcon isActive={activeTool === "cursor"} />
                </div>
              )}
              {activeSubTool == "free-hand" && (
                <div
                  className={`tool-button ${
                    activeTool === "free-hand" ? "active" : ""
                  }`}
                  onClick={() => {
                    setActiveTool("free-hand");
                  }}
                >
                  <div className="tooltip">free hand (h)</div>
                  <FreeMoveIcon isActive={activeTool === "free-hand"} />
                </div>
              )}
              {activeSubTool == "delete" && (
                <div
                  className={`tool-button ${
                    activeTool === "delete" ? "active" : ""
                  }`}
                  onClick={() => {
                    setActiveTool("delete");
                  }}
                >
                  <div className="tooltip">delete (x)</div>
                  <DeleteIcon isActive={activeTool === "delete"} />
                </div>
              )}
              {activeModule !== "visualization" && (
                <div
                  className="drop-down-option-button"
                  ref={dropdownRef}
                  onClick={() => {
                    setOpenDrop(!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
                        className="option-list"
                        onClick={() => {
                          setOpenDrop(false);
                          setActiveTool("delete");
                          setActiveSubTool("delete");
                        }}
                      >
                        <div className="active-option">
                          {activeSubTool === "delete" && <TickIcon />}
                        </div>
                        <DeleteIcon isActive={false} />
                        <div className="option">Delete</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");
                  }}
                >
                  <div className="tooltip">draw wall (q)</div>
                  <WallIcon isActive={activeTool === "draw-wall"} />
                </div>
                <div
                  className={`tool-button ${
                    activeTool === "draw-zone" ? "active" : ""
                  }`}
                  onClick={() => {
                    setActiveTool("draw-zone");
                  }}
                >
                  <div className="tooltip">draw zone (e)</div>
                  <ZoneIcon isActive={activeTool === "draw-zone"} />
                </div>
                <div
                  className={`tool-button ${
                    activeTool === "draw-aisle" ? "active" : ""
                  }`}
                  onClick={() => {
                    setActiveTool("draw-aisle");
                  }}
                >
                  <div className="tooltip">draw asile (r)</div>
                  <AsileIcon isActive={activeTool === "draw-aisle"} />
                </div>
                <div
                  className={`tool-button ${
                    activeTool === "draw-floor" ? "active" : ""
                  }`}
                  onClick={() => {
                    setActiveTool("draw-floor");
                  }}
                >
                  <div className="tooltip">draw floor (t)</div>
                  <FloorIcon isActive={activeTool === "draw-floor"} />
                </div>
              </div>
            </>
          )}
          {activeModule === "builder" && (
            <>
              <div className="split"></div>
              <div className="draw-tools">
                <div
                  className={`tool-button ${
                    activeTool === "measure" ? "active" : ""
                  }`}
                  onClick={() => {
                    setActiveTool("measure");
                  }}
                >
                  <div className="tooltip">measure scale (m)</div>
                  <MeasureToolIcon isActive={activeTool === "measure"} />
                </div>
              </div>
            </>
          )}
          {activeModule === "simulation" && (
            <>
              <div className="split"></div>
              <div className="draw-tools">
                <div
                  className={`tool-button ${
                    activeTool === "pen" ? "active" : ""
                  }`}
                  onClick={() => {
                    setActiveTool("pen");
                  }}
                >
                  <div className="tooltip">pen</div>
                  <PenIcon isActive={activeTool === "pen"} />
                </div>
              </div>
            </>
          )}
          {activeModule === "visualization" && (
            <>
              <div className="split"></div>
              <div className="draw-tools">
                <div
                  className={`tool-button`}
                  onClick={() => {
                    handleSaveTemplate({
                      addTemplate,
                      floatingWidget,
                      widgets3D,
                      selectedZone,
                      templates,
                      visualizationSocket,
                    });
                  }}
                >
                  <div className="tooltip">save template</div>
                  <SaveTemplateIcon isActive={false} />
                </div>
              </div>
            </>
          )}
          <div className="split"></div>
          <div className="general-options">
            <div
              className={`tool-button ${
                activeTool === "comment" ? "active" : ""
              }`}
              onClick={() => {
                setActiveTool("comment");
              }}
            >
              <div className="tooltip">comment</div>
              <CommentIcon isActive={activeTool === "comment"} />
            </div>
            {toggleThreeD && (
              <div
                className={`tool-button ${
                  activeTool === "play" ? "active" : ""
                }`}
                onClick={() => {
                  setIsPlaying(!isPlaying);
                }}
              >
                <div className="tooltip">play (ctrl + p)</div>
                <PlayIcon isActive={activeTool === "play"} />
              </div>
            )}
          </div>
          {activeModule === "builder" && (
            <>
              <div className="split"></div>
              <div
                className={`toggle-threed-button${
                  toggleThreeD ? " toggled" : ""
                }`}
                onClick={toggleSwitch}
              >
                <div className="tooltip">toggle view (tab)</div>
                <div
                  className={`toggle-option${!toggleThreeD ? " active" : ""}`}
                >
                  2d
                </div>
                <div
                  className={`toggle-option${toggleThreeD ? " active" : ""}`}
                >
                  3d
                </div>
              </div>
            </>
          )}
        </div>
      ) : (
        <>
          {activeModule !== "simulation" && (
            <button className="exitPlay" onClick={() => setIsPlaying(false)}>
              X
            </button>
          )}
        </>
      )}
    </>
  );
};

export default Tools;
