import { useEffect, useRef } from "react";

export interface CanvasKeyboardActions {
  onDelete: () => void;
  onUndo: () => void;
  onRedo: () => void;
  onSelectAll: () => void;
  onCopy: () => void;
  onPaste: () => void;
  onDuplicate: () => void;
  onEscape: () => void;
  setSpacePanning: (active: boolean) => void;
  isInputFocused: () => boolean;
}

export function useCanvasKeyboard(actions: CanvasKeyboardActions) {
  const actionsRef = useRef(actions);
  actionsRef.current = actions;

  useEffect(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      const a = actionsRef.current;
      if (a.isInputFocused()) return;

      const ctrl = event.ctrlKey || event.metaKey;

      if (event.key === "Delete" || event.key === "Backspace") {
        event.preventDefault();
        a.onDelete();
        return;
      }
      if (ctrl && event.key === "z" && !event.shiftKey) {
        event.preventDefault();
        a.onUndo();
        return;
      }
      if (ctrl && (event.key === "y" || (event.key === "z" && event.shiftKey))) {
        event.preventDefault();
        a.onRedo();
        return;
      }
      if (ctrl && event.key === "a") {
        event.preventDefault();
        a.onSelectAll();
        return;
      }
      if (ctrl && event.key === "c") {
        event.preventDefault();
        a.onCopy();
        return;
      }
      if (ctrl && event.key === "v") {
        event.preventDefault();
        a.onPaste();
        return;
      }
      if (ctrl && event.key === "d") {
        event.preventDefault();
        a.onDuplicate();
        return;
      }
      if (event.key === "Escape") {
        a.onEscape();
        return;
      }
      if (event.key === " " && !ctrl) {
        event.preventDefault();
        a.setSpacePanning(true);
      }
    };

    const handleKeyUp = (event: KeyboardEvent) => {
      if (event.key === " ") {
        actionsRef.current.setSpacePanning(false);
      }
    };

    window.addEventListener("keydown", handleKeyDown);
    window.addEventListener("keyup", handleKeyUp);
    return () => {
      window.removeEventListener("keydown", handleKeyDown);
      window.removeEventListener("keyup", handleKeyUp);
    };
  }, []);
}
