import React, { useEffect } from "react";
import useModuleStore from "../store/ui/useModuleStore";
import { useSocketStore, 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 { getAllProjects } from "../services/dashboard/getAllProjects";
import { viewProject } from "../services/dashboard/viewProject";
import { getUserData } from "../functions/getUserData";
import { SceneProvider } from "../modules/scene/sceneContext";
import { sharedWithMeProjects } from "../services/dashboard/sharedWithMeProject";
import { handleCanvasCursors } from "../utils/mouseUtils/handleCanvasCursors";
import MainScene from "../components/layout/scenes/MainScene";
import ComparisonScene from "../components/layout/scenes/ComparisonScene";

const Project: React.FC = () => {
    let navigate = useNavigate();
    const echo = useLogger();
    const { setActiveModule } = useModuleStore();
    const { projectId } = useParams();
    const { setProjectName } = useProjectName();
    const { userId, email, organization } = getUserData();
    const { selectedUser } = useSelectedUserStore();
    const { isLogListVisible } = useLogger();
    const { activeTool } = useActiveTool();

    useEffect(() => {
        if (!email || !userId) {
            console.error("User data not found in localStorage");
            navigate("/page-not-found");
            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);
                    navigate(`/not_found#project_not_found#${projectId}`);
                }
            } catch (error) {
                console.error("Error fetching projects:", error);
            }
        };

        fetchProjects();

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

    useEffect(() => {
        setActiveModule("builder");
        if (email) {
            const token = localStorage.getItem("token");
            const refreshToken = localStorage.getItem("refreshToken");
            echo.warn("Validating token");
            if (token && refreshToken) {
                useSocketStore.getState().initializeSocket(email, organization, token, refreshToken);
            }
            echo.success("Project initialized and loaded successfully");
        } else {
            navigate("/");
        }

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

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

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

export default Project;
