import React, { useEffect } from "react";
import {
  useLoadingProgress,
  useRenameModeStore,
  useSaveVersion,
  useSelectedAssets,
  useSelectedComment,
  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 RegularDropDown from "../../ui/inputs/RegularDropDown";
import RenameTooltip from "../../ui/features/RenameTooltip";
import { setAssetsApi } from "../../../services/factoryBuilder/asset/floorAsset/setAssetsApi";
import { useParams } from "react-router-dom";
import { useSceneContext } from "../../../modules/scene/sceneContext";
import { useVersionHistoryStore } from "../../../store/builder/useVersionHistoryStore";
import { useVersionContext } from "../../../modules/builder/version/versionContext";
import VersionSaved from "../sidebarRight/versionHisory/VersionSaved";
import Footer from "../../footer/Footer";
import ThreadChat from "../../ui/collaboration/ThreadChat";

function MainScene() {
  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 { clearComparisonProduct } = useComparisonProduct();
  const { selectedFloorItem, setSelectedFloorItem } = useSelectedFloorItem();
  const { selectedAssets,setSelectedAssets } = useSelectedAssets();
  const { assetStore, productStore } = useSceneContext();
  const { products } = productStore();
  const { setName } = assetStore();
  const { projectId } = useParams()
  const { isRenameMode, setIsRenameMode } = useRenameModeStore();
  const { versionHistory } = useVersionHistoryStore();
  const { selectedVersionStore } = useVersionContext();
  const { selectedVersion, setSelectedVersion } = selectedVersionStore();
  const { selectedComment, commentPositionState } = useSelectedComment();

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

  useEffect(() => {
    if (versionHistory.length > 0) {
      setSelectedVersion(versionHistory[0])
    }
  }, [versionHistory])

  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) {
      setMainProduct(product.productUuid, product.productName);
    }
  };

  const handleObjectRename = async (newName: string) => {
    if (!projectId) return
    if (selectedFloorItem) {
      console.log('selectedFloorItem.userData.modelUuid: ', selectedFloorItem.userData.modelUuid);
      console.log(' newName: ',  newName);
      console.log('projectId: ', projectId);
      setAssetsApi({
        modelUuid: selectedFloorItem.userData.modelUuid,
        modelName: newName,
        projectId,
        versionId: selectedVersion?.versionId || ''
      }).then(() => {
        selectedFloorItem.userData = {
          ...selectedFloorItem.userData,
          modelName: newName
        };
        setSelectedFloorItem(selectedFloorItem);
        setIsRenameMode(false);
        setName(selectedFloorItem.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 && !isVersionSaved && <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 || selectedAssets.length === 1) && <RenameTooltip name={selectedFloorItem?.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 && isVersionSaved && !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;
