import React, { useEffect } from "react";
import useModuleStore from "../store/useModuleStore";
import {
  useSocketStore,
  useOrganization,
  useUserName,
  useSaveVersion,
  useProjectName,
  useActiveTool,
} from "../store/builder/store";
import { useNavigate, useParams } 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 { useToggleStore } from "../store/useUIToggleStore";
import { getAllProjects } from "../services/dashboard/getAllProjects";
import { viewProject } from "../services/dashboard/viewProject";
import ComparisonSceneProvider from "../components/layout/scenes/ComparisonSceneProvider";
import MainSceneProvider from "../components/layout/scenes/MainSceneProvider";
import { getUserData } from "../functions/getUserData";
import { SceneProvider } from "../modules/scene/sceneContext";
import { getVersionHistoryApi } from "../services/factoryBuilder/versionControl/getVersionHistoryApi";
import { useVersionHistoryStore } from "../store/builder/useVersionHistoryStore";
import { VersionProvider } from "../modules/builder/version/versionContext";
import { sharedWithMeProjects } from "../services/dashboard/sharedWithMeProject";
import { handleCanvasCursors } from "../utils/mouseUtils/handleCanvasCursors";

const Project: React.FC = () => {
  let navigate = useNavigate();
  const echo = useLogger();
  const { setToggleUI } = useToggleStore();
  const { setActiveModule } = useModuleStore();
  const { setUserName } = useUserName();
  const { setOrganization } = useOrganization();
  const { isVersionSaved } = useSaveVersion();
  const { projectId } = useParams();
  const { setProjectName } = useProjectName();
  const { userId, email, organization, userName } = getUserData();
  const { selectedUser } = useSelectedUserStore();
  const { isLogListVisible } = useLogger();
  const { setVersions } = useVersionHistoryStore();
  const { activeTool } = useActiveTool();

  useEffect(() => {
    if (!email || !userId) {
      console.error("User data not found in localStorage");
      return;
    }

    const fetchProjects = async () => {
      try {
        const projects = await getAllProjects(userId, organization);
        const shared = await sharedWithMeProjects();

        const allProjects = [...(projects?.Projects || []), ...(shared || [])];

        const matchedProject = allProjects.find(
          (val: any) => val.projectUuid === projectId || val._id === projectId
        );

        if (matchedProject) {
          setProjectName(matchedProject.projectName);
          await viewProject(organization, matchedProject._id, userId);
        } else {
          console.warn("Project not found with given ID:", projectId);
        }
      } catch (error) {
        console.error("Error fetching projects:", error);
      }
    };

    fetchProjects();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    if (!projectId) return;
    getVersionHistoryApi(projectId)
      .then((data) => {
        const versions: VersionHistory = [];
        data.versions.forEach((version: any) => {
          versions.push({
            version: version.version,
            versionId: version.versionId,
            versionName: version.versionName,
            versionDescription: version.description,
            timeStamp: version.createdAt,
            createdBy: version.createdBy.userName,
          });
        });
        setVersions(versions);
      })
      .catch(() => {
        console.error("Error fetching version history");
      });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [projectId]);

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

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

  useEffect(() => {
    handleCanvasCursors(activeTool);
  }, [activeTool]);

  return (
    <div className="project-main">
      <SceneProvider layout="Main Layout">
        <VersionProvider>
          <MainSceneProvider />
        </VersionProvider>
      </SceneProvider>
      <SceneProvider layout="Comparison Layout">
        <VersionProvider>
          <ComparisonSceneProvider />
        </VersionProvider>
      </SceneProvider>
      {selectedUser && <FollowPerson />}
      {isLogListVisible && (
        <RenderOverlay>
          <LogList />
        </RenderOverlay>
      )}
    </div>
  );
};

export default Project;
