import { generateUniqueId } from "../../../functions/generateUniqueId";
import { getUserData } from "../../../functions/getUserData";
import { useDroppedObjectsStore } from "../../../store/visualization/useDroppedObjectsStore";
import { determinePosition } from "./determinePosition";
import { getActiveProperties } from "./getActiveProperties";

interface HandleDropProps {
  widgetSubOption: any;
  visualizationSocket: any;
  selectedZone: any;
  setFloatingWidget: (value: any) => void;
  event: React.DragEvent<HTMLDivElement>;
  projectId?: string,
  versionId?: string
}

export const createHandleDrop = ({
  widgetSubOption,
  visualizationSocket,
  selectedZone,
  setFloatingWidget,
  event,
  projectId,
  versionId
}: HandleDropProps) => {
  event.preventDefault();
  try {
    const { userId, organization, email } = getUserData();

    const data = event.dataTransfer.getData("text/plain");
    if (widgetSubOption === "3D") return;
    if (!data || selectedZone.zoneName === "") return;

    const droppedData = JSON.parse(data);
    const canvasElement = document.getElementById("work-space-three-d-canvas");
    if (!canvasElement) return;

    const rect = canvasElement.getBoundingClientRect();
    const relativeX = event.clientX - rect.left;
    const relativeY = event.clientY - rect.top;

    // Widget dimensions
    const widgetWidth = droppedData.width ?? 125;
    const widgetHeight = droppedData.height ?? 100;

    // Center the widget at cursor
    const centerOffsetX = widgetWidth / 2;
    const centerOffsetY = widgetHeight / 2;

    const adjustedX = relativeX - centerOffsetX;
    const adjustedY = relativeY - centerOffsetY;

    const finalPosition = determinePosition(rect, adjustedX, adjustedY);
    const [activeProp1, activeProp2] = getActiveProperties(finalPosition);

    let finalY = 0;
    let finalX = 0;

    if (activeProp1 === "top") {
      finalY = adjustedY;
    } else {
      finalY = rect.height - (adjustedY + widgetHeight);
    }

    if (activeProp2 === "left") {
      finalX = adjustedX;
    } else {
      finalX = rect.width - (adjustedX + widgetWidth);
    }

    // Clamp to boundaries
    finalX = Math.max(0, Math.min(rect.width - widgetWidth, finalX));
    finalY = Math.max(0, Math.min(rect.height - widgetHeight, finalY));

    const boundedPosition = {
      ...finalPosition,
      [activeProp1]: finalY,
      [activeProp2]: finalX,
      [activeProp1 === "top" ? "bottom" : "top"]: "auto",
      [activeProp2 === "left" ? "right" : "left"]: "auto",
    };

    const newObject = {
      ...droppedData,
      id: generateUniqueId(),
      position: boundedPosition,
    };

    const existingZone =
      useDroppedObjectsStore.getState().zones[selectedZone.zoneName];
    if (!existingZone) {
      useDroppedObjectsStore
        .getState()
        .setZone(selectedZone.zoneName, selectedZone.zoneUuid);
    }

    const addFloatingWidget = {
      organization,
      widget: newObject,
      zoneUuid: selectedZone.zoneUuid,
      versionId,
      projectId,
      userId
    };

    if (visualizationSocket) {
      visualizationSocket.emit("v1:viz-float:add", addFloatingWidget);
    }

    useDroppedObjectsStore
      .getState()
      .addObject(selectedZone.zoneName, newObject);

    const droppedObjectsStore = useDroppedObjectsStore.getState();
    const currentZone = droppedObjectsStore.zones[selectedZone.zoneName];

    if (currentZone && currentZone.zoneUuid === selectedZone.zoneUuid) {
      // console.log(
      //   `Objects for Zone ${selectedZone.zoneUuid}:`,
      //   currentZone.objects
      // );
      setFloatingWidget(currentZone.objects);
    } else {
      console.warn("Zone not found or zoneUuid mismatch");
    }
  } catch (error) {
    echo.error("Failed to drop widget");
    console.error("Error in handleDrop:", error);
  }
};
