import React, { useEffect } from "react";
import useModuleStore from "../store/useModuleStore";
import {
	useSocketStore,
	useOrganization,
	useUserName,
	useWallItems,
	useSaveVersion,
	useViewSceneStore,
	useProjectName,
	useRenameModeStore,
	useSelectedFloorItem,
	useZones,
	useSelectedComment,
} 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 ThreadChat from "../components/ui/collaboration/ThreadChat";

const Project: React.FC = () => {
	let navigate = useNavigate();
	const echo = useLogger();
	const { setToggleUI } = useToggleStore();
	const { setActiveModule } = useModuleStore();
	const { setUserName } = useUserName();
	const { setOrganization } = useOrganization();
	const { setWallItems } = useWallItems();
	const { setZones } = useZones();
	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 { selectedComment, commentPositionState } = useSelectedComment();

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

		getAllProjects(userId, organization).then((projects) => {
			if (!projects || !projects.Projects) return;
			const filterProject = projects?.Projects.find((val: any) => val.projectUuid === projectId || val._id === projectId)
			setProjectName(filterProject.projectName)
			viewProject(organization, filterProject._id, userId).then((viewedProject) => {
			});
		}).catch(() => {
			console.error("Error fetching projects")
		})

	}, []);

	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")
		})
	}, [projectId])

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

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

	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>
			)}
			{(commentPositionState !== null || selectedComment !== null) && <ThreadChat />}
		</div>
	);
};

export default Project;
