import { createSignal } from "solid-js";

interface UndoAction {
  type: string;
  description: string;
  timestamp: number;
  undo: () => void;
}

const MAX_UNDO_HISTORY = 50;

const [undoStack, setUndoStack] = createSignal<UndoAction[]>([]);
const [redoStack, setRedoStack] = createSignal<UndoAction[]>([]);

export function useUndoRedo() {
  const canUndo = () => undoStack().length > 0;
  const canRedo = () => redoStack().length > 0;

  const pushUndo = (action: Omit<UndoAction, "timestamp">) => {
    const undoAction: UndoAction = {
      ...action,
      timestamp: Date.now(),
    };
    setUndoStack((stack) => {
      const newStack = [undoAction, ...stack].slice(0, MAX_UNDO_HISTORY);
      return newStack;
    });
    // Clear redo stack when new action is performed
    setRedoStack([]);
  };

  const undo = () => {
    const stack = undoStack();
    if (stack.length === 0) return;

    const [action, ...rest] = stack;
    setUndoStack(rest);

    // Execute undo
    action.undo();

    // Push to redo stack
    setRedoStack((stack) => [action, ...stack]);
  };

  const redo = () => {
    const stack = redoStack();
    if (stack.length === 0) return;

    const [action, ...rest] = stack;
    setRedoStack(rest);

    // Re-execute the original action (stored in undo function)
    // This is a simplified version - in a full implementation,
    // you'd store both undo and redo functions
    setUndoStack((stack) => [action, ...stack]);
  };

  const clearHistory = () => {
    setUndoStack([]);
    setRedoStack([]);
  };

  const getLastUndoDescription = () => {
    const stack = undoStack();
    return stack.length > 0 ? stack[0].description : null;
  };

  const getLastRedoDescription = () => {
    const stack = redoStack();
    return stack.length > 0 ? stack[0].description : null;
  };

  return {
    canUndo,
    canRedo,
    pushUndo,
    undo,
    redo,
    clearHistory,
    getLastUndoDescription,
    getLastRedoDescription,
    undoStack,
    redoStack,
  };
}

// Global keyboard shortcuts for undo/redo
export function setupUndoRedoShortcuts(undo: () => void, redo: () => void) {
  const handleKeyDown = (e: KeyboardEvent) => {
    // Check for Ctrl+Z (undo) or Cmd+Z on Mac
    if ((e.ctrlKey || e.metaKey) && e.key === "z" && !e.shiftKey) {
      e.preventDefault();
      undo();
      return;
    }

    // Check for Ctrl+Shift+Z (redo) or Cmd+Shift+Z on Mac
    if ((e.ctrlKey || e.metaKey) && e.key === "z" && e.shiftKey) {
      e.preventDefault();
      redo();
      return;
    }

    // Check for Ctrl+Y (redo) on Windows
    if ((e.ctrlKey || e.metaKey) && e.key === "y") {
      e.preventDefault();
      redo();
      return;
    }
  };

  document.addEventListener("keydown", handleKeyDown);
  return () => document.removeEventListener("keydown", handleKeyDown);
}