import React, { useEffect } from "react";
import useModuleStore from "../store/useModuleStore";
import {
  useSocketStore,
  useOrganization,
  useUserName,
  useWallItems,
  useZones,
  useSaveVersion,
} from "../store/builder/store";
import { useNavigate } from "react-router-dom";
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 { 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 { selectedUser } = useSelectedUserStore();
  const { isLogListVisible } = useLogger();

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

  useEffect(() => {
    setAssets([]);
    setWallItems([]);
    setZones([]);
    setActiveModule("builder");
    const email = localStorage.getItem("email");
    if (email) {
      const Organization = email.split("@")[1].split(".")[0];
      useSocketStore.getState().initializeSocket(email, Organization);
      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;
