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 { getZonesApi } from "../../../services/realTimeVisulization/zoneData/getZones";


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

type FormattedZoneData = Record<
  string,
  {
    activeSides: Side[];
    panelOrder: Side[];
    lockedPanels: Side[];
    zoneCentrePoint: number[];
    widgets: Widget[];
  }
>;
type Widget = {
  id: string;
  type: string;
  title: string;
  panel: Side;
  data: any;
};
type Zone = {
  zoneId: string;
  zoneName: string;
  points: number[][];
  layer: number;
};

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

  useEffect(() => {
    async function GetZoneData() {
      try {
        const response: { data: Zone[] } | undefined = await getZonesApi(
          "hexrfactory"
        );

        if (!response || !response.data) {
          return;
        }
        const formattedData = response?.data?.reduce<FormattedZoneData>(
          (acc, zone) => {
            acc[zone.zoneName] = {
              activeSides: [],
              panelOrder: [],
              lockedPanels: [],
              zoneCentrePoint: [],
              widgets: [],
            };
            return acc;
          },
          {}
        );
        setZonesData(formattedData);
      } catch (error) { }
    }
    GetZoneData();
  }, []);

  useEffect(() => {

    console.log('zonesData: ', zonesData);
  }, [zonesData]);

  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 || [],
          widgets: selectedZone.widgets || [],
        },
      };
    });
  }, [selectedZone]);

  return (
    <div
      ref={containerRef}
      id="real-time-vis-canvas"
      className={`realTime-viz canvas ${!isPlaying ? "playActiveFalse" : ""}`}
      style={{
        height: isPlaying ? "100vh" : "",
        left: isPlaying ? "0%" : "",
      }}
    >
      <div
        className="scene-container"
        style={{ height: "100%", width: "100%" }}
      >
        <Scene />
      </div>
      {!isPlaying && (
        <AddButtons
          hiddenPanels={hiddenPanels}
          setHiddenPanels={setHiddenPanels}
          selectedZone={selectedZone}
          setSelectedZone={setSelectedZone}
        />
      )}
      <DisplayZone
        zonesData={zonesData}
        selectedZone={selectedZone}
        setSelectedZone={setSelectedZone}
      />
      <Panel
        selectedZone={selectedZone}
        hiddenPanels={hiddenPanels}
        setSelectedZone={setSelectedZone}
      />{" "}
    </div>
  );
};

export default RealTimeVisulization;
