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/handleSaveTemplate";
import { usePlayButtonStore } from "../../store/usePlayButtonStore";
import useTemplateStore from "../../store/useTemplateStore";
import { useSelectedZoneStore } from "../../store/useZoneStore";
import {
  useActiveTool,
  useAddAction,
  useDeleteModels,
  useDeletePointOrLine,
  useMovePoint,
  useRefTextUpdate,
  useSelectedWallItem,
  useToggleView,
  useToolMode,
  useTransformMode,
} from "../../store/store";
import useToggleStore from "../../store/useUIToggleStore";

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

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

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

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

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

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

  useEffect(() => {
    setActiveTool(activeSubTool);
    setActiveSubTool(activeSubTool);
  }, [activeModule]);

  const toggleSwitch = () => {
    if (toggleThreeD) {
      setSelectedWallItem(null);
      setDeleteModels(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
      }
    };
    const handleEscKeyPress = (event: KeyboardEvent) => {
      if (event.key === "Escape") {
        setIsPlaying(false); // Set isPlaying to false when Escape key is pressed
      }
    };
    document.addEventListener("mousedown", handleOutsideClick);
    document.addEventListener("keydown", handleEscKeyPress); // Listen for ESC key

    return () => {
      document.removeEventListener("mousedown", handleOutsideClick);
      document.removeEventListener("keydown", handleEscKeyPress); // Clean up the event listener
    };
  }, []);
  useEffect(() => {
    if (!toggleThreeD) {
      setToggleUI(false);
    }
  }, [toggleThreeD]);

  useEffect(() => {
    setToolMode(null);
    setDeleteModels(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 {
          setDeleteModels(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");
                    }}
                  >
                    <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>
                )}
                {activeSubTool == "delete" && (
                  <div
                    className={`tool-button ${
                      activeTool === "delete" ? "active" : ""
                    }`}
                    onClick={() => {
                      setActiveTool("delete");
                    }}
                  >
                    <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");
                    }}
                    title="Wall"
                  >
                    <WallIcon isActive={activeTool === "draw-wall"} />
                  </div>
                  <div
                    className={`tool-button ${
                      activeTool === "draw-zone" ? "active" : ""
                    }`}
                    onClick={() => {
                      setActiveTool("draw-zone");
                    }}
                    title="Zone"
                  >
                    <ZoneIcon isActive={activeTool === "draw-zone"} />
                  </div>
                  <div
                    className={`tool-button ${
                      activeTool === "draw-aisle" ? "active" : ""
                    }`}
                    onClick={() => {
                      setActiveTool("draw-aisle");
                    }}
                    title="Aisle"
                  >
                    <AsileIcon isActive={activeTool === "draw-aisle"} />
                  </div>
                  <div
                    className={`tool-button ${
                      activeTool === "draw-floor" ? "active" : ""
                    }`}
                    onClick={() => {
                      setActiveTool("draw-floor");
                    }}
                    title="Floor"
                  >
                    <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");
                    }}
                    title="Measure"
                  >
                    <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");
                    }}
                  >
                    <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>
              {toggleThreeD && (
                <div
                  className={`tool-button ${
                    activeTool === "play" ? "active" : ""
                  }`}
                  onClick={() => {
                    setIsPlaying(!isPlaying);
                  }}
                >
                  <PlayIcon isActive={activeTool === "play"} />
                </div>
              )}
            </div>
            {activeModule === "builder" && (
              <>
                <div className="split"></div>
                <div
                  className={`toggle-threed-button${
                    toggleThreeD ? " toggled" : ""
                  }`}
                  onClick={toggleSwitch}
                >
                  <div
                    className={`toggle-option${!toggleThreeD ? " active" : ""}`}
                  >
                    2d
                  </div>
                  <div
                    className={`toggle-option${toggleThreeD ? " active" : ""}`}
                  >
                    3d
                  </div>
                </div>
              </>
            )}
          </div>
        </>
      ) : (
        <>
          {activeModule !== "simulation" && (
            <div className="exitPlay" onClick={() => setIsPlaying(false)}>
              X
            </div>
          )}
        </>
      )}
    </>
  );
};

export default Tools;
