import { useEffect } from "react";
import { useEditorStore } from "../../store/editorStore";

export const useKeyboardMovement = () => {
  const {
    selectedObjectIds,
    objects,
    updateObject,
    deleteObject,
    copySelectedObjects,
    pasteCopiedObjects,
    tool,
    layerRef,
    groupObjects,
    ungroupObjects,
    undoObjects,
    redoObjects,
  } = useEditorStore();

  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      const target = e.target as HTMLElement;
      if (
        target.tagName === "INPUT" ||
        target.tagName === "TEXTAREA" ||
        target.isContentEditable
      ) {
        return;
      }

      if ((e.metaKey || e.ctrlKey) && (e.key === "z" || e.key === "Z")) {
        e.preventDefault();
        if (e.shiftKey) {
          redoObjects();
        } else {
          undoObjects();
        }
        return;
      }

      if ((e.metaKey || e.ctrlKey) && (e.key === "y" || e.key === "Y")) {
        e.preventDefault();
        redoObjects();
        return;
      }

      if (tool !== "select") {
        return;
      }

      // Handle Delete and Backspace keys
      if (e.key === "Delete" || e.key === "Backspace") {
        if (selectedObjectIds.length > 0) {
          e.preventDefault();
          useEditorStore.getState().commitObjectHistoryBeforeChange();
          selectedObjectIds.forEach((id) =>
            deleteObject(id, { skipHistory: true }),
          );
          return;
        }
      }

      // Handle Command/Ctrl + G for grouping/ungrouping
      if ((e.metaKey || e.ctrlKey) && e.key === "g") {
        e.preventDefault();
        if (selectedObjectIds.length === 1) {
          const selectedObject = objects.find(
            (obj) => obj.id === selectedObjectIds[0]
          );
          // اگر group انتخاب شده، ungroup کن
          if (selectedObject?.type === "group") {
            ungroupObjects(selectedObject.id);
            return;
          }
        }
        // اگر چند object انتخاب شده، group کن
        if (selectedObjectIds.length >= 2) {
          groupObjects(selectedObjectIds);
          return;
        }
      }

      if ((e.metaKey || e.ctrlKey) && e.key === "c") {
        if (selectedObjectIds.length > 0) {
          e.preventDefault();
          copySelectedObjects();
        }
        return;
      }

      if ((e.metaKey || e.ctrlKey) && e.key === "v") {
        e.preventDefault();
        pasteCopiedObjects();
        return;
      }

      if (selectedObjectIds.length === 0) {
        return;
      }

      const step = e.shiftKey ? 10 : 1;
      let deltaX = 0;
      let deltaY = 0;

      switch (e.key) {
        case "ArrowUp":
          e.preventDefault();
          deltaY = -step;
          break;
        case "ArrowDown":
          e.preventDefault();
          deltaY = step;
          break;
        case "ArrowLeft":
          e.preventDefault();
          deltaX = -step;
          break;
        case "ArrowRight":
          e.preventDefault();
          deltaX = step;
          break;
        default:
          return;
      }

      useEditorStore.getState().commitObjectHistoryBeforeChange();

      // Move all selected objects
      selectedObjectIds.forEach((id) => {
        const selectedObject = objects.find((obj) => obj.id === id);
        if (!selectedObject) return;

        const newX = (selectedObject.x || 0) + deltaX;
        const newY = (selectedObject.y || 0) + deltaY;

        updateObject(id, {
          x: newX,
          y: newY,
        });

        if (layerRef?.current) {
          const maskedGroup = layerRef.current.findOne(`#masked-${id}`);
          const regularNode = layerRef.current.findOne(`#${id}`);
          const node = maskedGroup || regularNode;
          if (node) {
            node.x(newX);
            node.y(newY);
            layerRef.current.batchDraw();
          }
        }
      });
    };

    window.addEventListener("keydown", handleKeyDown);

    return () => {
      window.removeEventListener("keydown", handleKeyDown);
    };
  }, [
    selectedObjectIds,
    objects,
    updateObject,
    deleteObject,
    copySelectedObjects,
    pasteCopiedObjects,
    tool,
    layerRef,
    groupObjects,
    ungroupObjects,
    undoObjects,
    redoObjects,
  ]);
};
