import React, { useEffect, useState, useRef } from "react";
import { usePlayButtonStore } from "../../../store/usePlayButtonStore";
import Panel from "./Panel";
import AddButtons from "./AddButtons";
import { useSelectedZoneStore } from "../../../store/useZoneStore";
import DisplayZone from "./DisplayZone";
import Scene from "../../../modules/scene/scene";
import useModuleStore from "../../../store/useModuleStore";
import { useDroppedObjectsStore, useZones } from "../../../store/store";
import DroppedObjects from "./DroppedFloatingWidgets";



type Side = "top" | "bottom" | "left" | "right";

type FormattedZoneData = Record<
  string,
  {
    activeSides: Side[];
    panelOrder: Side[];
    lockedPanels: Side[];
    zoneId: string;
    zoneViewPortTarget: number[];
    zoneViewPortPosition: number[]
    widgets: Widget[];
  }
>;
type Widget = {
  id: string;
  type: string;
  title: string;
  panel: Side;
  data: any;
};

const RealTimeVisulization: React.FC = () => {
  const [hiddenPanels, setHiddenPanels] = React.useState<Side[]>([]);
  const containerRef = useRef<HTMLDivElement>(null);
  const { isPlaying } = usePlayButtonStore();
  const { activeModule } = useModuleStore();
  const [droppedObjects, setDroppedObjects] = useState<any[]>([]);
  const [zonesData, setZonesData] = useState<FormattedZoneData>({});
  const { selectedZone, setSelectedZone } = useSelectedZoneStore();
  const { zones } = useZones()

  useEffect(() => {
    const data = Array.isArray(zones) ? zones : [];

    const formattedData = data.reduce<FormattedZoneData>((acc, zone) => {
      acc[zone.zoneName] = {
        activeSides: [],
        panelOrder: [],
        lockedPanels: [],
        zoneId: zone.zoneId,
        zoneViewPortTarget: zone.viewPortCenter,
        zoneViewPortPosition: zone.viewPortposition,
        widgets: [],
      };
      return acc;
    }, {});

    setZonesData(formattedData);
  }, [zones]);

  useEffect(() => {
    setZonesData((prev) => {
      if (!selectedZone) return prev;
      return {
        ...prev,
        [selectedZone.zoneName]: {
          ...prev[selectedZone.zoneName], // Keep existing properties
          activeSides: selectedZone.activeSides || [],
          panelOrder: selectedZone.panelOrder || [],
          lockedPanels: selectedZone.lockedPanels || [],
          zoneId: selectedZone.zoneId || "",
          zoneViewPortTarget: selectedZone.zoneViewPortTarget || [],
          zoneViewPortPosition: selectedZone.zoneViewPortPosition || [],
          widgets: selectedZone.widgets || [],
        },
      };
    });
  }, [selectedZone]);

  // const handleDrop = (event: React.DragEvent<HTMLDivElement>) => {
  //   console.log("Drop event fired! ✅");
  //   event.preventDefault();

  //   const data = event.dataTransfer.getData("text/plain");
  //   if (!data) {
  //     console.log("❌ No data received on drop!");
  //     return;
  //   }

  //   try {
  //     const droppedData = JSON.parse(data);
  //     console.log("✅ Dropped Data:", droppedData);

  //     console.log('droppedData: ', droppedData);
  //     setDroppedObjects((prev) => [...prev, droppedData]); // ✅ Add to state
  //     console.log(droppedObjects);
  //   } catch (error) {
  //     console.error("❌ Error parsing dropped data:", error);
  //   }
  // };
  const handleDrop = (event: React.DragEvent<HTMLDivElement>) => {
    event.preventDefault();
    const data = event.dataTransfer.getData("text/plain"); // Use "text/plain" to match the drag event

    if (data) {
      const droppedData = JSON.parse(data);
      useDroppedObjectsStore.getState().addObject(droppedData); // Add to Zustand store
    }
  };

  return (
    <div
      ref={containerRef}
      id="real-time-vis-canvas"
      className={`realTime-viz canvas ${isPlaying ? "playingFlase" : ""}`}
      style={{
        height: isPlaying || activeModule !== "visualization" ? "100vh" : "",
        width: isPlaying || activeModule !== "visualization" ? "100vw" : "",
        left: isPlaying || activeModule !== "visualization" ? "0%" : "",
      }}
    >
      <div
        className="scene-container"
        style={{
          height: "100%",
          width: "100%",
          borderRadius: isPlaying || activeModule !== "visualization" ? "" : "6px",
        }}
        onDrop={(event) => handleDrop(event)}
        onDragOver={(event) => event.preventDefault()}
      >
      
        <Scene />
      </div>
      {activeModule === "visualization" && (
        <>
          <DisplayZone
            zonesData={zonesData}
            selectedZone={selectedZone}
            setSelectedZone={setSelectedZone}
          />

          {!isPlaying && selectedZone?.zoneName !== "" && (
            <AddButtons
              hiddenPanels={hiddenPanels}
              setHiddenPanels={setHiddenPanels}
              selectedZone={selectedZone}
              setSelectedZone={setSelectedZone}
            />
          )}

          <Panel
            hiddenPanels={hiddenPanels}
            selectedZone={selectedZone}
            setSelectedZone={setSelectedZone}

          />
        </>
      )}
    </div>
  );
};

export default RealTimeVisulization;
