'use client';

import { useCallback, useEffect, useState } from 'react';
import { useCanvasStore } from '@lib/store/canvasStore';
import { useProjectStore } from '@lib/store/project';

interface UseCanvasKeyboardProps {
  undo: () => void;
  redo: () => void;
  saveHistory: () => void;
  save: () => void;
  switchNext: () => void;
  switchPrev: () => void;
  switchCanvas?: (id: string, type: 'asset' | 'storyboard') => Promise<void>;
  assets: any[];
  storyboards: any[];
  createGroup: () => string | null;
  selectedNodeIds: string[];
}

export function useCanvasKeyboard({
  undo,
  redo,
  saveHistory,
  save,
  switchNext,
  switchPrev,
  switchCanvas,
  assets,
  storyboards,
  createGroup,
  selectedNodeIds,
}: UseCanvasKeyboardProps) {
  const [clipboard, setClipboard] = useState<any>(null);
  const setNodes = useCanvasStore((state) => state.setNodes);
  const setEdges = useCanvasStore((state) => state.setEdges);
  const nodes = useCanvasStore((state) => state.nodes);
  const edges = useCanvasStore((state) => state.edges);
  const addNode = useCanvasStore((state) => state.addNode);

  const pasteNodes = useCallback((position: { x: number; y: number }) => {
    if (!clipboard) return;

    const newNode = {
      ...clipboard,
      id: `${clipboard.type}-${Date.now()}`,
      position: {
        x: position.x,
        y: position.y,
      },
      selected: true,
    };

    addNode(newNode);
  }, [clipboard, addNode]);

  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      // Ctrl/Cmd + Z - Undo
      if ((e.metaKey || e.ctrlKey) && e.key === 'z' && !e.shiftKey) {
        e.preventDefault();
        undo();
        return;
      }

      // Ctrl/Cmd + Shift + Z - Redo
      if ((e.metaKey || e.ctrlKey) && e.shiftKey && e.key === 'z') {
        e.preventDefault();
        redo();
        return;
      }

      // Ctrl/Cmd + Y - Redo (alternative)
      if ((e.metaKey || e.ctrlKey) && e.key === 'y') {
        e.preventDefault();
        redo();
        return;
      }

      // Ctrl/Cmd + S - Save
      if ((e.metaKey || e.ctrlKey) && e.key === 's') {
        e.preventDefault();
        save();
        return;
      }

      // Ctrl/Cmd + Tab - Switch to next canvas
      if ((e.metaKey || e.ctrlKey) && e.key === 'Tab' && !e.shiftKey) {
        e.preventDefault();
        switchNext();
        return;
      }

      // Ctrl/Cmd + Shift + Tab - Switch to previous canvas
      if ((e.metaKey || e.ctrlKey) && e.shiftKey && e.key === 'Tab') {
        e.preventDefault();
        switchPrev();
        return;
      }

      // Ctrl/Cmd + G - Create group from selected
      if ((e.metaKey || e.ctrlKey) && e.key === 'g') {
        e.preventDefault();
        if (selectedNodeIds.length >= 2) {
          createGroup();
        }
        return;
      }

      // Delete - Delete selected nodes
      if (e.key === 'Delete' || e.key === 'Backspace') {
        const selectedNodes = nodes.filter((n) => n.selected);
        if (selectedNodes.length > 0) {
          e.preventDefault();
          saveHistory();
          const selectedIds = selectedNodes.map((n) => n.id);
          setNodes((nds) => nds.filter((n) => !selectedIds.includes(n.id)));
          setEdges((eds) => eds.filter((e) =>
            !selectedIds.includes(e.source) && !selectedIds.includes(e.target)
          ));
        }
        return;
      }

      // Ctrl/Cmd + C - Copy
      if ((e.metaKey || e.ctrlKey) && e.key === 'c') {
        const selectedNode = nodes.find((n) => n.selected);
        if (selectedNode && selectedNode.type === 'appNode') {
          setClipboard(selectedNode);
        }
        return;
      }

      // Ctrl/Cmd + V - Paste
      if ((e.metaKey || e.ctrlKey) && e.key === 'v') {
        if (clipboard) {
          e.preventDefault();
          const centerX = window.innerWidth / 2;
          const centerY = window.innerHeight / 2;
          pasteNodes({ x: centerX, y: centerY });
        }
        return;
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [
    undo,
    redo,
    save,
    switchNext,
    switchPrev,
    createGroup,
    selectedNodeIds,
    nodes,
    edges,
    setNodes,
    setEdges,
    saveHistory,
    clipboard,
    pasteNodes,
  ]);

  return {
    clipboard,
    setClipboard,
    pasteNodes,
  };
}
