import React, { useEffect } from "react";
import {
  useLoadingProgress,
  useRenameModeStore,
  useSaveVersion,
  useSelectedFloorItem,
  useSocketStore,
  useWidgetSubOption,
} from "../../../store/builder/store";
import useModuleStore, { useThreeDStore } from "../../../store/useModuleStore";
import { usePlayButtonStore } from "../../../store/usePlayButtonStore";
import { useSelectedZoneStore } from "../../../store/visualization/useZoneStore";
import { useFloatingWidget } from "../../../store/visualization/useDroppedObjectsStore";
import { useSelectedUserStore } from "../../../store/collaboration/useCollabStore";
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 { createHandleDrop } from "../../../modules/visualization/functions/handleUiDrop";
import Scene from "../../../modules/scene/scene";
import {
  useComparisonProduct,
  useMainProduct,
} from "../../../store/simulation/useSimulationStore";
import { useProductContext } from "../../../modules/simulation/products/productContext";
import { useProductStore } from "../../../store/simulation/useProductStore";
import RegularDropDown from "../../ui/inputs/RegularDropDown";
import RenameTooltip from "../../ui/features/RenameTooltip";
import { setFloorItemApi } from "../../../services/factoryBuilder/assest/floorAsset/setFloorItemApi";
import { useAssetsStore } from "../../../store/builder/useAssetStore";
import { useParams } from "react-router-dom";
import { getUserData } from "../../../functions/getUserData";

function MainScene() {
  const { products } = useProductStore();
  const { setMainProduct } = useMainProduct();
  const { selectedProductStore } = useProductContext();
  const { selectedProduct } = selectedProductStore();
  const { isVersionSaved, setIsVersionSaved } = useSaveVersion();
  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 { comparisonProduct, clearComparisonProduct } = useComparisonProduct();
  const { selectedFloorItem, setSelectedFloorItem } = useSelectedFloorItem();
  const { setName } = useAssetsStore();
  const { projectId } = useParams()
  const { isRenameMode, setIsRenameMode } = useRenameModeStore();
  const { userName, userId, organization, email } = getUserData();

  useEffect(() => {
    if (activeModule !== 'simulation') {
      clearComparisonProduct();
      setIsVersionSaved(false);
    }
  }, [activeModule])

  const handleSelectLayout = (option: string) => {
    const product = products.find((product) => product.productName === option);
    if (product) {
      setMainProduct(product.productUuid, product.productName);
    }
  };
  const handleObjectRename = async (newName: string) => {
    if (!projectId) return
    let response = await setFloorItemApi(
      organization,
      selectedFloorItem.userData.modelUuid,
      newName,
      projectId
    );
    selectedFloorItem.userData = {
      ...selectedFloorItem.userData,
      modelName: newName
    };
    setSelectedFloorItem(selectedFloorItem);
    setIsRenameMode(false);
    setName(selectedFloorItem.userData.modelUuid, response.modelName);
  }

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

          {isRenameMode && selectedFloorItem?.userData.modelName && <RenameTooltip name={selectedFloorItem?.userData.modelName} onSubmit={handleObjectRename} />}
          {/* remove this later */}
          {activeModule === "builder" && !toggleThreeD && <SelectFloorPlan />}
        </>
      )}
      <div
        className={`scene-container${
          comparisonProduct?.productUuid ? " half-view" : ""
        }`}
        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
          })
        }
        onDragOver={(event) => event.preventDefault()}
      >
        <Scene layout="Main Layout" />
      </div>

      {selectedProduct && isVersionSaved && !isPlaying && activeModule === "simulation" && (
        <div className="selectLayout-wrapper">
          <RegularDropDown
            header={selectedProduct.productName}
            options={products.map((l) => l.productName)} // Pass layout names as options
            onSelect={handleSelectLayout}
            search={false}
          />
        </div>
      )}
    </>
  );
}

export default MainScene;
