import React, { useEffect } from "react";
import useModuleStore from "../store/useModuleStore";
import {
  useSocketStore,
  useOrganization,
  useUserName,
  useWallItems,
  useSaveVersion,
  useViewSceneStore,
  useProjectName,
  useRenameModeStore,
  useSelectedFloorItem,
  useZones,
} 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 { 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 { useToggleStore } from "../store/useUIToggleStore";
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";
import { useAssetsStore } from "../store/builder/useAssetStore";
import ComparisonSceneProvider from "../components/layout/scenes/ComparisonSceneProvider";
import MainSceneProvider from "../components/layout/scenes/MainSceneProvider";

const Project: React.FC = () => {
  let navigate = useNavigate();
  const echo = useLogger();
  const { setToggleUI } = useToggleStore();
  const { activeModule, setActiveModule } = useModuleStore();
  const { setAssets } = useAssetsStore();
  const { setUserName } = useUserName();
  const { setOrganization } = useOrganization();
  const { setWallItems } = useWallItems();
  const { setZones } = useZones();
  const { isVersionSaved } = useSaveVersion();
  const { setProducts } = 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();
  }, []);
  // console.log('isRenameMode: ', isRenameMode);

  const { selectedUser } = useSelectedUserStore();
  const { isLogListVisible } = useLogger();

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

  useEffect(() => {
    setAssets([]);
    setWallItems([]);
    setZones([]);
    setProducts([]);
    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
  }, []);

  return (
    <div className="project-main">
      <ComparisonSceneProvider />
      <MainSceneProvider />
      {selectedUser && <FollowPerson />}
      {isLogListVisible && (
        <RenderOverlay>
          <LogList />
        </RenderOverlay>
      )}
      {activeModule !== "market" && !selectedUser && <Footer />}
      <VersionSaved />
    </div>
  );
};

export default Project;
