import React, { useEffect, useRef, useState, useCallback } from "react";
import { useWidgetStore, Widget } from "../../../store/useWidgetStore";

import {
  useDroppedObjectsStore,
  useFloatingWidget,
} from "../../../store/visualization/useDroppedObjectsStore";
import { getSelect2dZoneData } from "../../../services/visulization/zone/getSelect2dZoneData";
import { getFloatingZoneData } from "../../../services/visulization/zone/getFloatingData";
import { get3dWidgetZoneData } from "../../../services/visulization/zone/get3dWidgetData";
import {
  MoveArrowLeft,
  MoveArrowRight,
} from "../../../components/icons/SimulationIcons";
import { InfoIcon } from "../../../components/icons/ExportCommonIcons";
import { usePlayButtonStore } from "../../../store/usePlayButtonStore";
import { useParams } from "react-router-dom";
import { getUserData } from "../../../functions/getUserData";
import { useVersionContext } from "../../builder/version/versionContext";

// Define the type for `Side`
type Side = "top" | "bottom" | "left" | "right";

interface HiddenPanels {
  [zoneUuid: string]: Side[];
}

interface DisplayZoneProps {
  zonesData: {
    [key: string]: {
      activeSides: Side[];
      panelOrder: Side[];
      lockedPanels: Side[];
      points: [];
      widgets: Widget[];
      zoneUuid: string;
      zoneName: string;
      zoneViewPortTarget: number[];
      zoneViewPortPosition: number[];
    };
  };
  selectedZone: {
    zoneName: string;
    activeSides: Side[];
    panelOrder: Side[];
    lockedPanels: Side[];
    zoneUuid: string;
    points: [];
    zoneViewPortTarget: number[];
    zoneViewPortPosition: number[];
    widgets: {
      id: string;
      type: string;
      title: string;
      panel: Side;
      data: any;
    }[];
  };
  setSelectedZone: React.Dispatch<
    React.SetStateAction<{
      zoneName: string;
      activeSides: Side[];
      panelOrder: Side[];
      lockedPanels: Side[];
      points: [];
      zoneUuid: string;
      zoneViewPortTarget: number[];
      zoneViewPortPosition: number[];
      widgets: {
        id: string;
        type: string;
        title: string;
        panel: Side;
        data: any;
      }[];
    }>
  >;
  hiddenPanels: HiddenPanels; // Updated prop type
  setHiddenPanels: React.Dispatch<React.SetStateAction<HiddenPanels>>; // Updated prop type
}

const DisplayZone: React.FC<DisplayZoneProps> = ({
  zonesData,
  selectedZone,
  setSelectedZone,
  hiddenPanels,
}) => {
  // Ref for the container element
  const containerRef = useRef<HTMLDivElement | null>(null);
  const scrollContainerRef = useRef<HTMLDivElement | null>(null);

  // State to track overflow visibility
  const [showLeftArrow, setShowLeftArrow] = useState(false);
  const [showRightArrow, setShowRightArrow] = useState(false);
  const { floatingWidget, setFloatingWidget } = useFloatingWidget();
  const { isPlaying } = usePlayButtonStore();
  const { userName, userId, organization, email } = getUserData();
  const { setSelectedChartId } = useWidgetStore();
  const { selectedVersionStore } = useVersionContext();
  const { selectedVersion } = selectedVersionStore();
  const { projectId } = useParams();
  // Function to calculate overflow state
  const updateOverflowState = useCallback(() => {
    const container = scrollContainerRef.current;
    if (container) {
      const isOverflowing = container.scrollWidth > container.clientWidth;
      const canScrollLeft = container.scrollLeft > 0;

      const canScrollRight =
        container.scrollLeft + container.clientWidth + 1 <
        container.scrollWidth;
      setShowLeftArrow(isOverflowing && canScrollLeft);
      setShowRightArrow(isOverflowing && canScrollRight);

      // 
      // 
    }
  }, []);

  useEffect(() => {
    const container = scrollContainerRef.current;
    if (!container) return;

    // Initial calculation after the DOM has been rendered
    const observer = new ResizeObserver(updateOverflowState);
    observer.observe(container);

    // Update on scroll
    const handleScroll = () => updateOverflowState();
    container.addEventListener("scroll", handleScroll);

    // Add mouse wheel listener for horizontal scrolling
    const handleWheel = (event: WheelEvent) => {
      if (Math.abs(event.deltaY) > Math.abs(event.deltaX)) {
        event.preventDefault();
        container.scrollBy({
          left: event.deltaY * 2,
          behavior: "smooth",
        });
      }
    };

    container.addEventListener("wheel", handleWheel, { passive: false });

    // Initial check
    updateOverflowState();

    return () => {
      observer.disconnect();
      container.removeEventListener("scroll", handleScroll);
      container.removeEventListener("wheel", handleWheel);
    };
  }, [updateOverflowState]);

  // Handle scrolling with navigation arrows
  const handleScrollLeft = () => {
    const container = scrollContainerRef.current;
    if (container) {
      container.scrollBy({
        left: -200,
        behavior: "smooth",
      });
    }
  };

  const handleScrollRight = () => {
    const container = scrollContainerRef.current;
    if (container) {
      container.scrollBy({
        left: 200,
        behavior: "smooth",
      });
    }
  };

  async function handleSelect2dZoneData(zoneUuid: string, zoneName: string) {
    try {
      if (selectedZone?.zoneUuid === zoneUuid) {
        return;
      }
      // setSelectedChartId(null);

      let response = await getSelect2dZoneData(zoneUuid, organization, projectId, selectedVersion?.versionId || '');

      // 
      let res = await getFloatingZoneData(zoneUuid, organization, projectId, selectedVersion?.versionId || '');
      // 

      setFloatingWidget(res);
      // Set the selected zone in the store
      useDroppedObjectsStore.getState().setZone(zoneName, zoneUuid);
      if (Array.isArray(res)) {
        res.forEach((val) => {
          useDroppedObjectsStore.getState().addObject(zoneName, val);
        });
      }

      setSelectedZone({
        zoneName,
        activeSides: response.activeSides || [],
        panelOrder: response.panelOrder || [],
        lockedPanels: response.lockedPanels || [],
        widgets: response.widgets || [],
        points: response.points || [],
        zoneUuid: zoneUuid,
        zoneViewPortTarget: response.viewPortTarget || [],
        zoneViewPortPosition: response.viewPortPosition || [],
      });
    } catch (error) {
      echo.error("Failed to select zone");
    }
  }

  return (
    <div
      ref={containerRef}
      id="zone-container"
      className={`zone-container ${selectedZone?.activeSides?.includes("bottom") &&
        !hiddenPanels[selectedZone.zoneUuid]?.includes("bottom")
        ? "bottom"
        : ""
        } ${isPlaying ? "visualization-playing" : ""}`}
    >
      {/* Left Arrow */}
      {showLeftArrow && (
        <button
          id="zone-preview-left-arrow"
          className="arrow left-arrow"
          onClick={handleScrollLeft}
        >
          <MoveArrowLeft />
        </button>
      )}

      {/* Scrollable Zones Container */}
      <div
        ref={scrollContainerRef}
        className="zones-wrapper"
        style={{ overflowX: "auto", whiteSpace: "nowrap" }}
      >
        {Object.keys(zonesData).length !== 0 ? (
          <>
            {Object.values(zonesData).map((zone, index) => (
              <>
                { }
                <div
                  key={index}
                  className={`zone ${selectedZone.zoneUuid === zone.zoneUuid ? "active" : ""
                    }`}
                  onClick={() => {

                    handleSelect2dZoneData(zonesData[zone.zoneUuid]?.zoneUuid, zone.zoneName)
                  }
                  }
                >
                  {zone.zoneName}
                </div>
              </>
            ))}
          </>
        ) : (
          <div className="no-zone">
            <InfoIcon />
            No zones? Create one!
          </div>
        )}
      </div>

      {/* Right Arrow */}
      {showRightArrow && (
        <button
          id="zone-preview-right-arrow"
          className="arrow right-arrow"
          onClick={handleScrollRight}
        >
          <MoveArrowRight />
        </button>
      )}
    </div>
  );
};

export default DisplayZone;
