import { useEffect } from "react";
import { useParams } from "react-router-dom";
import { useLoadingProgress, useRenameModeStore, useIsComparing, useSelectedComment, useWidgetSubOption, useToggleView, useCreateNewWindow } from "../../../store/builder/store";
import useModuleStore from "../../../store/ui/useModuleStore";
import { useSocketStore } from "../../../store/socket/useSocketStore";
import { usePlayButtonStore } from "../../../store/ui/usePlayButtonStore";
import { useSelectedZoneStore } from "../../../store/visualization/old/useZoneStore";
import { useFloatingWidget } from "../../../store/visualization/old/useDroppedObjectsStore";
import { useSelectedUserStore } from "../../../store/collaboration/useCollabStore";
import { createHandleDrop } from "../../../modules/visualization/functions/handleUiDrop";
import { useSimulationState } from "../../../store/simulation/useSimulationStore";
import { useSceneContext } from "../../../modules/scene/sceneContext";
import useRestStates from "../../../hooks/useResetStates";
import KeyPressListener from "../../../utils/shortcutkeys/handleShortcutKeys";
import LoadingPage from "../../templates/LoadingPage";
import ModuleToggle from "../../ui/ModuleToggle";
import SideBarLeft from "../sidebarLeft/SideBarLeft";
import SideBarRight from "../sidebarRight/SideBarRight";
// import RealTimeVisulization from "../../../modules/visualization/RealTimeVisulization";
import MarketPlace from "../../../modules/market/MarketPlace";
import Tools from "../../ui/Tools";
import SimulationPlayer from "../../ui/simulation/simulationPlayer";
import ControlsPlayer from "../controls/ControlsPlayer";
import SelectFloorPlan from "../../temporary/SelectFloorPlan";
import RegularDropDown from "../../ui/inputs/RegularDropDown";
import RenameTooltip from "../../ui/features/RenameTooltip";
import VersionSaved from "../sidebarRight/versionHisory/VersionSaved";
import Footer from "../../footer/Footer";
import ThreadChat from "../../ui/collaboration/threads/ThreadChat";
import Scene from "../../../modules/scene/scene";

import { recentlyViewedApi } from "../../../services/dashboard/recentlyViewedApi";
import { setAssetsApi } from "../../../services/builder/asset/floorAsset/setAssetsApi";
import { getVersionHistoryApi } from "../../../services/builder/versionControl/getVersionHistoryApi";
import { getUserData } from "../../../functions/getUserData";
import DashboardEditor from "../../SimulationDashboard/DashboardEditor";

function MainScene() {
    const { setMainState, clearComparisonState } = useSimulationState();
    const { isComparing, setIsComparing } = useIsComparing();
    const { activeModule } = useModuleStore();
    const { selectedUser } = useSelectedUserStore();
    const { loadingProgress } = useLoadingProgress();
    const { toggleView } = useToggleView();
    const { isPlaying } = usePlayButtonStore();
    const { widgetSubOption } = useWidgetSubOption();
    const { builderSocket, visualizationSocket } = useSocketStore();
    const { selectedZone } = useSelectedZoneStore();
    const { setFloatingWidget } = useFloatingWidget();
    const { assetStore, productStore, versionStore } = useSceneContext();
    const { products, selectedProduct } = productStore();
    const { versionHistory, setVersions, selectedVersion, setSelectedVersion } = versionStore();
    const { setName, selectedAssets, setSelectedAssets } = assetStore();
    const { projectId } = useParams();
    const { isRenameMode, setIsRenameMode } = useRenameModeStore();
    const { selectedComment, commentPositionState } = useSelectedComment();
    const { resetStates } = useRestStates();
    const { organization, userId } = getUserData();
    const { createNewWindow } = useCreateNewWindow();

    useEffect(() => {
        return () => {
            resetStates();
        };
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    useEffect(() => {
        if (builderSocket && projectId) {
            setTimeout(() => {
                builderSocket.emit("joinRoom", { projectId: projectId });
            }, 1000);
        }
    }, [builderSocket, projectId]);

    useEffect(() => {
        if (activeModule !== "simulation") {
            clearComparisonState();
            setIsComparing(false);
        }
    }, [activeModule, clearComparisonState, setIsComparing]);

    useEffect(() => {
        if (!projectId) return;

        getVersionHistoryApi(projectId)
            .then((data) => {
                if (!data.versions) return;
                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 (versionHistory.length > 0) {
            recentlyViewedApi().then((projects) => {
                const recent_opened_verisionID = (Object.values(projects?.RecentlyViewed || {})[0] as any)?.Present_version._id;
                if (recent_opened_verisionID && projects.RecentlyViewed[0]._id === projectId) {
                    const version = versionHistory.find((ver) => ver.versionId === recent_opened_verisionID);
                    if (version) {
                        setSelectedVersion(version);
                    }
                } else {
                    setSelectedVersion(versionHistory[0]);
                }
            });
        }
    }, [setSelectedVersion, versionHistory, projectId]);

    const handleSelectVersion = (option: string) => {
        const version = versionHistory.find((version) => version.versionName === option);
        if (version) {
            setSelectedVersion(version);
        }
    };

    const handleSelectProduct = (option: string) => {
        const product = products.find((product) => product.productName === option);
        if (product && selectedVersion) {
            const data = {
                productUuid: product.productUuid,
                productName: product.productName,
                versionUuid: selectedVersion.versionId,
                versionName: selectedVersion.versionName,
            };
            setMainState(data);
        }
    };

    const handleObjectRename = async (newName: string) => {
        if (!projectId) return;
        if (selectedAssets.length === 1) {
            if (!builderSocket?.connected) {
                setAssetsApi({
                    modelUuid: selectedAssets[0].userData.modelUuid,
                    assetId: selectedAssets[0].userData.assetId,
                    modelName: newName,
                    projectId,
                    versionId: selectedVersion?.versionId || "",
                })
                    .then((data) => {
                        if (data.message === "Model updated successfully" && data.data) {
                            setSelectedAssets(selectedAssets);
                            setIsRenameMode(false);
                            setName(selectedAssets[0].userData.modelUuid, newName);
                            echo.info(`Asset Renamed: ${newName}`);
                        } else {
                            echo.error(`Error Renaming Asset`);
                        }
                    })
                    .catch(() => {
                        echo.error(`Error Renaming Asset`);
                    });
            } else {
                const data = {
                    modelUuid: selectedAssets[0].userData.modelUuid,
                    assetId: selectedAssets[0].userData.assetId,
                    modelName: newName,
                    projectId,
                    versionId: selectedVersion?.versionId || "",
                    socketId: builderSocket?.id,
                    organization: organization,
                    userId: userId,
                };

                setIsRenameMode(false);
                builderSocket.emit("v1:model-asset:add", data);
            }
        }
    };

    return (
        <>
            {!selectedUser && (
                <>
                    <KeyPressListener />
                    {!createNewWindow && loadingProgress > 0 && <LoadingPage progress={loadingProgress} />}
                    {!isPlaying && (
                        <>
                            {!toggleView && !isComparing && <ModuleToggle />}
                            {activeModule !== "visualization" && (
                                <>
                                    <SideBarLeft />
                                    <SideBarRight />
                                </>
                            )}
                        </>
                    )}
                    {/* <RealTimeVisulization /> */}
                    {activeModule === "market" && <MarketPlace />}
                    {activeModule !== "market" && !isPlaying && !isComparing && <Tools />}
                    {isPlaying && activeModule === "simulation" && loadingProgress === 0 && <SimulationPlayer />}
                    {isPlaying && activeModule !== "simulation" && <ControlsPlayer />}
                    {activeModule === "visualization" && <DashboardEditor />}

                    {isRenameMode && selectedAssets.length === 1 && <RenameTooltip name={selectedAssets[0].userData.modelName} onSubmit={handleObjectRename} />}

                    {activeModule === "builder" && toggleView && <SelectFloorPlan />}

                    {selectedProduct && selectedVersion && isComparing && !isPlaying && activeModule === "simulation" && (
                        <div className="selectLayout-wrapper">
                            <RegularDropDown header={selectedVersion.versionName} options={versionHistory.map((v) => v.versionName)} onSelect={handleSelectVersion} search={false} />
                            <br />
                            <RegularDropDown header={selectedProduct.productName} options={products.map((l) => l.productName)} onSelect={handleSelectProduct} search={false} />
                        </div>
                    )}

                    <VersionSaved />
                </>
            )}

            {(commentPositionState !== null || selectedComment !== null) && <ThreadChat />}

            {activeModule !== "market" && !selectedUser && <Footer />}

            <div
                className="scene-container"
                id="work-space-three-d-canvas"
                style={{
                    // height: isPlaying || activeModule !== "visualization" ? "100vh" : "",
                    // width: isPlaying || activeModule !== "visualization" ? "100vw" : "",
                    // left: isPlaying || activeModule !== "visualization" ? "0%" : "",
                    // borderRadius: isPlaying || activeModule !== "visualization" ? "" : "6px",
                    height: "100vh",
                    width: "100vw",
                    left: "0%",
                    borderRadius: "",
                }}
                role="application"
                onDrop={(event) =>
                    createHandleDrop({
                        widgetSubOption,
                        visualizationSocket,
                        selectedZone,
                        setFloatingWidget,
                        event,
                        projectId,
                        versionId: selectedVersion?.versionId || "",
                    })
                }
                onDragOver={(event) => event.preventDefault()}
            >
                <Scene layout="Main Layout" />
            </div>
        </>
    );
}

export default MainScene;
