import { useEffect } from "react";
import { useParams } from "react-router-dom";
import { useLoadingProgress, useRenameModeStore, useIsComparing, useSelectedComment, useSocketStore, useWidgetSubOption } from "../../../store/builder/store";
import useModuleStore, { useThreeDStore } from "../../../store/ui/useModuleStore";
import { usePlayButtonStore } from "../../../store/ui/usePlayButtonStore";
import { useSelectedZoneStore } from "../../../store/visualization/useZoneStore";
import { useFloatingWidget } from "../../../store/visualization/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 { useBuilderStore } from "../../../store/builder/useBuilderStore";
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/ThreadChat";
import Scene from "../../../modules/scene/scene";

import { getUserData } from "../../../functions/getUserData";
import { recentlyViewed } from "../../../services/dashboard/recentlyViewed";
import { setAssetsApi } from "../../../services/factoryBuilder/asset/floorAsset/setAssetsApi";
import { getVersionHistoryApi } from "../../../services/factoryBuilder/versionControl/getVersionHistoryApi";

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

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

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

    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");
            });
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [projectId]);

    useEffect(() => {
        if (versionHistory.length > 0 && organization && userId) {
            recentlyViewed(organization, userId).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 (selectedFloorAsset) {
            setAssetsApi({
                modelUuid: selectedFloorAsset.userData.modelUuid,
                modelName: newName,
                projectId,
                versionId: selectedVersion?.versionId || "",
            }).then(() => {
                selectedFloorAsset.userData = { ...selectedFloorAsset.userData, modelName: newName };
                setSelectedFloorAsset(selectedFloorAsset);
                setIsRenameMode(false);
                setName(selectedFloorAsset.userData.modelUuid, newName);
            });
        } else if (selectedAssets.length === 1) {
            setAssetsApi({
                modelUuid: selectedAssets[0].userData.modelUuid,
                modelName: newName,
                projectId,
                versionId: selectedVersion?.versionId || "",
            }).then(() => {
                selectedAssets[0].userData = { ...selectedAssets[0].userData, modelName: newName };
                setSelectedAssets(selectedAssets);
                setIsRenameMode(false);
                setName(selectedAssets[0].userData.modelUuid, newName);
            });
        }
    };

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

                    {isRenameMode && (selectedFloorAsset?.userData.modelName || selectedAssets.length === 1) && <RenameTooltip name={selectedFloorAsset?.userData.modelName || selectedAssets[0].userData.modelName} onSubmit={handleObjectRename} />}
                    {/* remove this later */}
                    {activeModule === "builder" && !toggleThreeD && <SelectFloorPlan />}
                </>
            )}
            <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",
                }}
                role="application"
                onDrop={(event) =>
                    createHandleDrop({
                        widgetSubOption,
                        visualizationSocket,
                        selectedZone,
                        setFloatingWidget,
                        event,
                        projectId,
                        versionId: selectedVersion?.versionId || "",
                    })
                }
                onDragOver={(event) => event.preventDefault()}
            >
                <Scene layout="Main Layout" />
            </div>

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

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

            <VersionSaved />

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

export default MainScene;
