import React, { useEffect, useState } from "react";
import ModuleToggle from "../components/ui/ModuleToggle";
import SideBarLeft from "../components/layout/sidebarLeft/SideBarLeft";
import SideBarRight from "../components/layout/sidebarRight/SideBarRight";
import useModuleStore, { useThreeDStore } from "../store/useModuleStore";
import RealTimeVisulization from "../modules/visualization/RealTimeVisulization";
import Tools from "../components/ui/Tools";
import {
  useSocketStore,
  useFloorItems,
  useOrganization,
  useUserName,
  useWallItems,
  useZones,
  useLoadingProgress,
  useWidgetSubOption,
  useSaveVersion,
  useProjectName,
  useRenameModeStore,
  useSelectedFloorItem,
} from "../store/builder/store";
import { useNavigate, useParams } from "react-router-dom";
import { usePlayButtonStore } from "../store/usePlayButtonStore";
import MarketPlace from "../modules/market/MarketPlace";
import LoadingPage from "../components/templates/LoadingPage";
import KeyPressListener from "../utils/shortcutkeys/handleShortcutKeys";
import { useSelectedUserStore } from "../store/collaboration/useCollabStore";
import FollowPerson from "../components/templates/FollowPerson";
import Scene from "../modules/scene/scene";
import { createHandleDrop } from "../modules/visualization/functions/handleUiDrop";
import { useSelectedZoneStore } from "../store/visualization/useZoneStore";
import { useFloatingWidget } from "../store/visualization/useDroppedObjectsStore";
import { useLogger } from "../components/ui/log/LoggerContext";
import RenderOverlay from "../components/templates/Overlay";
import LogList from "../components/ui/log/LogList";
import Footer from "../components/footer/Footer";
import SelectFloorPlan from "../components/temporary/SelectFloorPlan";
import ControlsPlayer from "../components/layout/controls/ControlsPlayer";
import CompareLayOut from "../components/ui/compareVersion/CompareLayOut";
import { useToggleStore } from "../store/useUIToggleStore";
import RegularDropDown from "../components/ui/inputs/RegularDropDown";
import VersionSaved from "../components/layout/sidebarRight/versionHisory/VersionSaved";
import SimulationPlayer from "../components/ui/simulation/simulationPlayer";
import { useProductStore } from "../store/simulation/useProductStore";
import { getAllProjects } from "../services/dashboard/getAllProjects";
import { viewProject } from "../services/dashboard/viewProject";
import RenameTooltip from "../components/ui/features/RenameTooltip";
import { setFloorItemApi } from "../services/factoryBuilder/assest/floorAsset/setFloorItemApi";

const Project: React.FC = () => {
  let navigate = useNavigate();
  const echo = useLogger();
  const { setToggleUI } = useToggleStore();

  const { activeModule, setActiveModule } = useModuleStore();
  const { loadingProgress } = useLoadingProgress();
  const { setUserName } = useUserName();
  const { setOrganization } = useOrganization();
  const { setFloorItems } = useFloorItems();
  const { selectedFloorItem, setSelectedFloorItem } = useSelectedFloorItem();
  const { setWallItems } = useWallItems();
  const { setZones } = useZones();
  const { isVersionSaved } = useSaveVersion();
  const { products } = useProductStore();
  const { projectId } = useParams();
  const { setProjectName } = useProjectName();

  const generateThumbnail = async () => {
    const email = localStorage.getItem("email");
    const userId = localStorage.getItem("userId");
    try {
      if (!email || !userId) {
        console.error("User data not found in localStorage");
        return;
      }

      const emailParts = email.split("@");
      if (emailParts.length < 2) {
        console.error("Invalid email format");
        return;
      }

      const domainParts = emailParts[1].split(".");
      const Organization = domainParts[0];
      const projects = await getAllProjects(
        userId, Organization
      );
      const filterProject = projects?.Projects.find((val: any) => val.projectUuid === projectId || val._id
        === projectId)
      const viewedProject = await viewProject(
        Organization,
        filterProject._id,
        userId,
      );
      // console.log('filterProject.projectName: ', filterProject.projectName);
      setProjectName(filterProject.projectName)

    }
    catch {

    }
  }
  useEffect(() => {
    generateThumbnail();
  }, []);
  const { isRenameMode, setIsRenameMode } = useRenameModeStore();
  // console.log('isRenameMode: ', isRenameMode);

  useEffect(() => {
    if (!isVersionSaved) {
      setToggleUI(true, true);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isVersionSaved]);

  useEffect(() => {
    setFloorItems([]);
    setWallItems([]);
    setZones([]);
    setActiveModule("builder");
    const email = localStorage.getItem("email");
    if (email) {
      const Organization = email.split("@")[1].split(".")[0];
      const token = localStorage.getItem("token");
      if (token) {
        useSocketStore.getState().initializeSocket(email, Organization, token);
      }
      const name = localStorage.getItem("userName");
      if (Organization && name) {
        setOrganization(Organization);
        setUserName(name);
      }
      echo.success("Log in successful");
    } else {
      navigate("/");
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // global store
  const { toggleThreeD } = useThreeDStore();

  // simulation store
  const { isPlaying } = usePlayButtonStore();

  // collaboration store
  const { selectedUser } = useSelectedUserStore();
  const { isLogListVisible } = useLogger();

  // real-time visualization store
  const { widgetSubOption } = useWidgetSubOption();
  const { visualizationSocket } = useSocketStore();
  const { selectedZone } = useSelectedZoneStore();
  const { setFloatingWidget } = useFloatingWidget();

  const [selectedLayout, setSelectedLayout] = useState<string | null>(null); // Track selected layout

  const dummyLayouts = [
    { id: 1, name: "Layout 1" },
    { id: 2, name: "Layout 2" },
    { id: 3, name: "Layout 3" },
    { id: 4, name: "Layout 4" },
  ];

  const handleSelectLayout = (option: string) => {
    setSelectedLayout(option); // Set selected layout
    console.log("Selected layout:", option);
  };

  const handleObjectRename = async (newName: string) => {
    const email = localStorage.getItem("email") ?? "";
    const organization = email?.split("@")[1]?.split(".")[0];
    let response = await setFloorItemApi(
      organization,
      selectedFloorItem.userData.modelUuid,
      newName
    );
    selectedFloorItem.userData.name = newName;
    setSelectedFloorItem(selectedFloorItem);
    setIsRenameMode(false);
    setFloorItems((prevFloorItems: any[]) =>
      prevFloorItems.map((floorItems) =>
        floorItems.modelUuid === selectedFloorItem.userData.modelUuid
          .id
          ? { ...floorItems, modelName: response.modelName }
          : floorItems
      )
    );
  }


  return (
    <div className="project-main">
      {!selectedUser && (
        <>
          <KeyPressListener />
          {loadingProgress > 0 && <LoadingPage progress={loadingProgress} />}
          {!isPlaying && (
            <>
              {toggleThreeD && <ModuleToggle />}
              <SideBarLeft />
              <SideBarRight />
            </>
          )}
          <RealTimeVisulization />
          {activeModule === "market" && <MarketPlace />}
          {activeModule !== "market" && !isPlaying && !isVersionSaved && (
            <Tools />
          )}
          {isPlaying && activeModule === "simulation" && <SimulationPlayer />}
          {isPlaying && activeModule !== "simulation" && <ControlsPlayer />}

          {/* remove this later */}
          {activeModule === "builder" && !toggleThreeD && <SelectFloorPlan />}
        </>
      )}
      <div
        className="scene-container"
        id="work-space-three-d-canvas"
        style={{
          height: isPlaying || activeModule !== "visualization" ? "100vh" : "",
          width: isPlaying || activeModule !== "visualization" ? "100vw" : "",
          left: isPlaying || activeModule !== "visualization" ? "0%" : "",
          borderRadius:
            isPlaying || activeModule !== "visualization" ? "" : "6px",
        }}
        role="application"
        onDrop={(event) =>
          createHandleDrop({
            widgetSubOption,
            visualizationSocket,
            selectedZone,
            setFloatingWidget,
            event,
            projectId
          })
        }
        onDragOver={(event) => event.preventDefault()}
      >
        <Scene />
      </div>
      {isRenameMode && selectedFloorItem?.userData.name && <RenameTooltip name={selectedFloorItem?.userData.name} onSubmit={handleObjectRename} />}
      {selectedUser && <FollowPerson />}
      {isLogListVisible && (
        <RenderOverlay>
          <LogList />
        </RenderOverlay>
      )}
      {activeModule !== "market" && !selectedUser && <Footer />}
      {isVersionSaved && activeModule === "simulation" && (
        <>
          <div className="initial-selectLayout-wrapper">
            <RegularDropDown
              header={selectedLayout ?? "Layout 1"}
              options={products.map((l) => l.productName)} // Pass layout names as options
              onSelect={handleSelectLayout}
              search={false}
            />
          </div>
          <CompareLayOut dummyLayouts={dummyLayouts} />
        </>
      )}
      <VersionSaved />
    </div>
  );
};

export default Project;
