import React, { useEffect, useState, useRef } from "react";
import { usePlayButtonStore } from "../../store/usePlayButtonStore";
import Panel from "./widgets/panel/Panel";
import AddButtons from "./widgets/panel/AddButtons";
import { useSelectedZoneStore } from "../../store/visualization/useZoneStore";
import DisplayZone from "./zone/DisplayZone";
import useModuleStore from "../../store/useModuleStore";
import { getZone2dData } from "../../services/visulization/zone/getZoneData";
import SocketRealTimeViz from "./socket/realTimeVizSocket.dev";
import RenderOverlay from "../../components/templates/Overlay";
import ConfirmationPopup from "../../components/layout/confirmationPopup/ConfirmationPopup";
import DroppedObjects from "./widgets/floating/DroppedFloatingWidgets";
import EditWidgetOption from "../../components/ui/menu/EditWidgetOption";
import { useEditWidgetOptionsStore, useRightClickSelected, useRightSelected, } from "../../store/visualization/useZone3DWidgetStore";
import OuterClick from "../../utils/outerClick";
import { useWidgetStore } from "../../store/useWidgetStore";
import { useNavigate, useParams } from "react-router-dom";
import { getUserData } from "../../functions/getUserData";
import { useVersionContext } from "../builder/version/versionContext";
import { useSceneContext } from "../scene/sceneContext";

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

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

// Define the type for HiddenPanels, where keys are zone IDs and values are arrays of hidden sides
interface HiddenPanels {
  [zoneUuid: string]: Side[];
}

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

  const { setRightSelect } = useRightSelected();
  const { editWidgetOptions, setEditWidgetOptions } = useEditWidgetOptionsStore();
  const { rightClickSelected, setRightClickSelected } = useRightClickSelected();
  const [openConfirmationPopup, setOpenConfirmationPopup] = useState(false);
  const { setSelectedChartId } = useWidgetStore();
  const [waitingPanels, setWaitingPanels] = useState(null);
  const { selectedVersionStore } = useVersionContext();
  const { selectedVersion } = selectedVersionStore();
  const { projectId } = useParams();
  const navigate = useNavigate();
  const { zoneStore } = useSceneContext();
  const { zones } = zoneStore();


  OuterClick({
    contextClassName: [
      "chart-container",
      "floating",
      "sidebar-right-wrapper",
      "card",
      "dropdown-menu",
      "dropdown-options",
    ],
    setMenuVisible: () => setSelectedChartId(null),
  });

  const { organization } = getUserData();

  useEffect(() => {
    if (!projectId || !selectedVersion) return;
    getZone2dData(organization, projectId, selectedVersion?.versionId || '').then((response) => {
      // console.log('response: ', response);
      if (!response) return;
      // if (response.status === 401) {
      //   console.log("force logout");
      //   navigate("/");
      //   return;
      // }
      if (!Array.isArray(response)) {
        return;
      }
      const formattedData = response.reduce<FormattedZoneData>(
        (acc, zone) => {

          acc[zone.zoneUuid] = {
            activeSides: [],
            panelOrder: [],
            lockedPanels: [],
            points: zone.points,
            zoneUuid: zone.zoneUuid,
            zoneName: zone.zoneName,
            zoneViewPortTarget: zone.viewPortTarget,
            zoneViewPortPosition: zone.viewPortPosition,
            widgets: [],
          };
          return acc;
        }, {}
      );
      // console.log('formattedData: ', formattedData);
      setZonesData(formattedData);
    })

  }, [activeModule, selectedVersion?.versionId]);

  // Removed `zones` from dependencies

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

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      const editWidgetOptions = document.querySelector(
        ".editWidgetOptions-wrapper"
      );
      if (
        editWidgetOptions &&
        !editWidgetOptions.contains(event.target as Node)
      ) {
        setRightClickSelected(null);
        setRightSelect(null);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [setRightClickSelected, setRightSelect]);

  const [canvasDimensions, setCanvasDimensions] = useState({
    width: 0,
    height: 0,
  });
  useEffect(() => {
    const canvas = document.getElementById("work-space-three-d-canvas");
    if (!canvas) return;

    const updateCanvasDimensions = () => {
      const rect = canvas.getBoundingClientRect();
      setCanvasDimensions({
        width: rect.width,
        height: rect.height,
      });
    };

    updateCanvasDimensions();
    const resizeObserver = new ResizeObserver(updateCanvasDimensions);
    resizeObserver.observe(canvas);

    return () => resizeObserver.unobserve(canvas);
  }, []);

  return (
    <>
      <style>
        {`
    :root {
      --realTimeViz-container-width: ${canvasDimensions.width};
      --realTimeViz-container-height: ${canvasDimensions.height};
    }
  `}
      </style>
      <div
        ref={containerRef}
        className="realTime-viz"
        id="real-time-vis-canvas"
        style={{
          height: isPlaying || activeModule !== "visualization" ? "100vh" : "",
          width: isPlaying || activeModule !== "visualization" ? "100vw" : "",
          left: isPlaying || activeModule !== "visualization" ? "0%" : "",
          borderRadius:
            isPlaying || activeModule !== "visualization" ? "" : "6px",
        }}
      >
        <div className="realTime-viz-wrapper">
          {openConfirmationPopup && (
            <RenderOverlay>
              <ConfirmationPopup
                message={"Are you sure want to delete?"}
                onConfirm={() => console.log("Confirmed")}
                onCancel={() => setOpenConfirmationPopup(false)}
              />
            </RenderOverlay>
          )}
          {activeModule === "visualization" && selectedZone.zoneName !== "" && (
            <DroppedObjects />
          )}
          {activeModule === "visualization" && <SocketRealTimeViz />}

          {activeModule === "visualization" &&
            editWidgetOptions &&
            rightClickSelected && (
              <EditWidgetOption
                options={[
                  "Duplicate",
                  "Vertical Move",
                  "Horizontal Move",
                  "RotateX",
                  "RotateY",
                  "Delete",
                ]}
                onClick={(e) => {
                  setRightSelect(e);
                  setEditWidgetOptions(false);
                }}
              />
            )}

          {activeModule === "visualization" && (
            <>
              <DisplayZone
                zonesData={zonesData}
                selectedZone={selectedZone}
                setSelectedZone={setSelectedZone}
                hiddenPanels={hiddenPanels}
                setHiddenPanels={setHiddenPanels}
              />

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

              <Panel
                selectedZone={selectedZone}
                setSelectedZone={setSelectedZone}
                hiddenPanels={hiddenPanels}
                setZonesData={setZonesData}
                waitingPanels={waitingPanels}
              />
            </>
          )}
        </div>
      </div>
    </>
  );
};

export default RealTimeVisulization;
