import { useEffect } from "react";
import type { EditorRefActions } from "../Editor";

interface UseKeyboardOptions {
  onSave: () => void;
  onNewNote?: () => void;
}

export const useKeyboard = (editorRef: React.RefObject<EditorRefActions | null>, options: UseKeyboardOptions) => {
  useEffect(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      const ctrl = event.metaKey || event.ctrlKey;

      // Ctrl+Enter → save
      if (ctrl && event.key === "Enter") {
        event.preventDefault();
        options.onSave();
        return;
      }

      // Ctrl+N → new note (global)
      if (ctrl && event.key === "n") {
        event.preventDefault();
        options.onNewNote?.();
        return;
      }

      // Formatting shortcuts (only when editor is focused)
      const editor = editorRef.current;
      if (!editor) return;
      const activeTag = (document.activeElement as HTMLElement)?.tagName;
      if (activeTag !== "TEXTAREA") return;

      // Ctrl+D → insert current datetime
      if (ctrl && event.key === "d") {
        event.preventDefault();
        const now = new Date();
        const pad = (n: number) => String(n).padStart(2, "0");
        const dateStr = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}`;
        editor.insertText(dateStr);
        return;
      }

      // Ctrl+B → **bold**
      if (ctrl && event.key === "b") {
        event.preventDefault();
        editor.insertText("", "**", "**");
        return;
      }

      // Ctrl+I → _italic_
      if (ctrl && event.key === "i") {
        event.preventDefault();
        editor.insertText("", "_", "_");
        return;
      }

      // Ctrl+K → [text](url)
      if (ctrl && event.key === "k") {
        event.preventDefault();
        const selected = editor.getSelectedContent();
        if (selected) {
          editor.insertText("", "[", "](url)");
        } else {
          editor.insertText("[text](url)");
          // Select the word "text" for quick replacement
          const pos = editor.getCursorPosition();
          editor.setCursorPosition(pos - "](url)".length - "text".length, pos - "](url)".length);
        }
        return;
      }

      // Ctrl+Shift+C → - [ ] checkbox
      if (ctrl && event.shiftKey && event.key === "C") {
        event.preventDefault();
        const lineNum = editor.getCursorLineNumber();
        const line = editor.getLine(lineNum);
        editor.setLine(lineNum, "- [ ] " + line);
        return;
      }

      // Tab → indent list item
      if (event.key === "Tab") {
        const lineNum = editor.getCursorLineNumber();
        const line = editor.getLine(lineNum);
        if (/^(\s*[-*+]|\s*\d+\.)/.test(line)) {
          event.preventDefault();
          if (event.shiftKey) {
            // Shift+Tab → unindent
            editor.setLine(lineNum, line.replace(/^  /, ""));
          } else {
            editor.setLine(lineNum, "  " + line);
          }
        }
      }
    };

    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [editorRef, options, options.onNewNote]);
};
