import React, { useEffect } from "react";
import { useNavigate, useParams } from "react-router-dom";
import useModuleStore from "../store/ui/useModuleStore";
import { useSocketStore } from "../store/socket/useSocketStore";
import { useSelectedUserStore } from "../store/collaboration/useCollabStore";
import { useProjectName, useActiveTool } from "../store/builder/store";
import { handleCanvasCursors } from "../utils/mouseUtils/handleCanvasCursors";

import { getUserData } from "../functions/getUserData";
import { viewProjectApi } from "../services/dashboard/viewProjectApi";
import { getAllProjectsApi } from "../services/dashboard/getAllProjectsApi";
import { sharedWithMeProjectsApi } from "../services/dashboard/sharedWithMeProjectApi";

import { useLogger } from "../components/ui/log/LoggerContext";
import { SceneProvider } from "../modules/scene/sceneContext";

import FollowPerson from "../components/templates/FollowPerson";
import RenderOverlay from "../components/templates/Overlay";
import LogList from "../components/ui/log/LogList";
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 {
        builderSocket,
        visualizationSocket,
        threadSocket,
        initializeBuilderSocket,
        initializeVisualizationSocket,
        initializeThreadSocket,
        disconnectBuilderSocket,
        disconnectVisualizationSocket,
        disconnectThreadSocket,
    } = useSocketStore();
    const { projectId } = useParams();
    const { setProjectName } = useProjectName();
    const { userId, email } = getUserData();
    const { selectedUser } = useSelectedUserStore();
    const { isLogListVisible } = useLogger();
    const { activeTool } = useActiveTool();

    useEffect(() => {
        setActiveModule("builder");
        if (!email || !userId) {
            console.error("User data not found in localStorage");
            navigate("/page-not-found");
            return;
        }
        const fetchProjects = async () => {
            try {
                const projects = await getAllProjectsApi();
                const shared = await sharedWithMeProjectsApi();

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

                const matchedProject = allProjects.find((val: any) => val.projectUuid === projectId || val._id === projectId);
                if (matchedProject) {
                    setProjectName(matchedProject.projectName);
                    await viewProjectApi(matchedProject._id);
                } 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
    }, [projectId]);

    useEffect(() => {
        const token = localStorage.getItem("token");
        const refreshToken = localStorage.getItem("refreshToken");
        
        if (token && refreshToken && projectId) {
            echo.warn("Validating token");
            initializeBuilderSocket(token, refreshToken, projectId);
            echo.success("Builder socket initialized");
        } else {
            navigate("/");
            return;
        }

        return () => {
            if (projectId && builderSocket) {
                disconnectBuilderSocket(projectId);
            }
        };
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [projectId, builderSocket]);

    useEffect(() => {
        const token = localStorage.getItem("token");
        const refreshToken = localStorage.getItem("refreshToken");
        
        if (token && refreshToken && projectId) {
            initializeVisualizationSocket(token, refreshToken, projectId);
            echo.success("Visualization socket initialized");
        } else {
            navigate("/");
            return;
        }

        return () => {
            if (projectId && visualizationSocket) {
                disconnectVisualizationSocket(projectId);
            }
        };
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [projectId, visualizationSocket]);

    useEffect(() => {
        const token = localStorage.getItem("token");
        const refreshToken = localStorage.getItem("refreshToken");
        
        if (token && refreshToken && projectId) {
            initializeThreadSocket(token, refreshToken, projectId);
            echo.success("Thread socket initialized");
        } else {
            navigate("/");
            return;
        }

        return () => {
            if (projectId && threadSocket) {
                disconnectThreadSocket(projectId);
            }
        };
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [projectId, threadSocket]);

    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;
