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 { useZones } from "../../../store/store";



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 [zonesData, setZonesData] = useState<FormattedZoneData>({});
  const { selectedZone, setSelectedZone } = useSelectedZoneStore();
  const { zones } = useZones()

  useEffect(() => {
    const data = Array.isArray(zones) ? zones : [];
    console.log('data: ', data);
    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>) => {
    event.preventDefault();
    const canvas = document.querySelector(".scene-container");
    if (canvas) {
      // Extract relevant properties manually
      const dragEvent = new DragEvent("drop", {
        bubbles: true,
        cancelable: true,
        dataTransfer: event.dataTransfer, // Attach dataTransfer manually ✅
      });

      console.log('dragEvent: ', dragEvent);
      canvas.dispatchEvent(dragEvent);
    }
  };


  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={handleDrop}
      >
        {/* {objects.map((obj) => (
          <mesh key={obj.id} position={obj.position}>
            <boxGeometry args={[1, 1, 1]} />
            <meshStandardMaterial color="green" />
          </mesh>
        ))} */}
        <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;
