import { useEffect, useMemo } from "react";
import { Canvas } from "@react-three/fiber";
import { KeyboardControls } from "@react-three/drei";
import { SceneProvider } from "./sceneContext";

import Builder from "../builder/builder";
import Visualization from "../visualization/visualization";
import Setup from "./setup/setup";
import Simulation from "../simulation/simulation";
import Collaboration from "../collaboration/collaboration";
import useModuleStore from "../../store/useModuleStore";
import { useParams } from "react-router-dom";
import { getAllProjects } from "../../services/dashboard/getAllProjects";
import { getUserData } from "../../components/Dashboard/functions/getUserData";
import { useLoadingProgress, useSocketStore } from "../../store/builder/store";
import { useAssetsStore } from "../../store/builder/useAssetStore";

export default function Scene({ layout }: { readonly layout: 'Main Layout' | 'Comparison Layout' }) {
    const map = useMemo(() => [
        { name: "forward", keys: ["ArrowUp", "w", "W"] },
        { name: "backward", keys: ["ArrowDown", "s", "S"] },
        { name: "left", keys: ["ArrowLeft", "a", "A"] },
        { name: "right", keys: ["ArrowRight", "d", "D"] },
    ], []);
    const { assets } = useAssetsStore();
    const { userId, organization } = getUserData();
    const { activeModule } = useModuleStore();
    const { projectId } = useParams();
    const { projectSocket } = useSocketStore();
    const { loadingProgress } = useLoadingProgress();
    const handleUpdatingProject = async () => {
        if (!projectId) return;
        try {
            const projects = await getAllProjects(userId, organization);
            let projectUuid = projects.Projects.find(
                (val: any) => val.projectUuid === projectId || val._id === projectId
            );


            if (activeModule === "builder" && loadingProgress !== 1) {
                const canvas =
                    document.getElementById("sceneCanvas")?.children[0]?.children[0];
                const screenshotDataUrl = (canvas as HTMLCanvasElement)?.toDataURL("image/png");
                setTimeout(() => {
                    const updateProjects = {
                        projectId: projectUuid,
                        organization,
                        userId,
                        projectName: projectUuid.projectName,
                        thumbnail: screenshotDataUrl,
                    };
                    if (projectSocket) {
                        projectSocket.emit("v1:project:update", updateProjects);
                    }
                }, 8000);
            } else {
                const canvas =
                    document.getElementById("sceneCanvas")?.children[0]?.children[0];
                const screenshotDataUrl = (canvas as HTMLCanvasElement)?.toDataURL("image/png");
                const updateProjects = {
                    projectId: projectUuid,
                    organization,
                    userId,
                    projectName: projectUuid.projectName,
                    thumbnail: screenshotDataUrl,
                };
                // console.log('screenshotDataUrl: ', screenshotDataUrl);
                // console.log('updateProjects: ', updateProjects);
                if (projectSocket) {
                    projectSocket.emit("v1:project:update", updateProjects);
                }
            }

        } catch (error) { }
    };
    useEffect(() => {
        handleUpdatingProject()
    }, [activeModule, assets, loadingProgress])

    return (
        <SceneProvider layout={layout}>
            <KeyboardControls map={map}>
                <Canvas
                    id="sceneCanvas"
                    shadows
                    color="#aaaa"
                    eventPrefix="client"
                    onContextMenu={(e) => {
                        e.preventDefault();
                    }}
                    onCreated={(e) => {
                        e.scene.background = null;
                    }}
                    gl={{ powerPreference: "high-performance", antialias: true, preserveDrawingBuffer: true }}
                >
                    <Setup />
                    <Collaboration />
                    <Builder />
                    <Simulation />
                    <Visualization />
                </Canvas>
            </KeyboardControls>
        </SceneProvider>
    );
}