import { useEffect } from "react";
import { invoke } from "@tauri-apps/api/core";
import { actions } from "@/lib/store";
import { toast } from "sonner";

interface ShortcutHandlers {
  onOpenCommandPalette: () => void;
  onOpenQuickOpen: () => void;
  onToggleTerminal: () => void;
  onSearchInFiles: () => void;
  onGoToLine: () => void;
  onSplitEditor: () => void;
}

export function useKeyboardShortcuts({
  onOpenCommandPalette,
  onOpenQuickOpen,
  onToggleTerminal,
  onSearchInFiles,
  onGoToLine,
  onSplitEditor,
}: ShortcutHandlers) {
  useEffect(() => {
    const handler = async (e: KeyboardEvent) => {
      const ctrl = e.ctrlKey || e.metaKey;

      if (ctrl && e.shiftKey && e.key === "P") {
        e.preventDefault();
        onOpenCommandPalette();
        return;
      }

      if (ctrl && e.key === "p") {
        e.preventDefault();
        onOpenQuickOpen();
        return;
      }

      if (ctrl && e.key === "b") {
        e.preventDefault();
        actions.toggleSidebar();
        return;
      }

      if (ctrl && e.key === "s") {
        e.preventDefault();
        const state = actions.getState();
        const activeTab = state.tabs.find((t) => t.path === state.activeTabPath);
        if (activeTab) {
          try {
            await invoke("write_file", { path: activeTab.path, contents: activeTab.content });
            actions.markSaved(activeTab.path);
            toast.success("Saved");
          } catch (err) {
            toast.error("Failed to save: " + String(err));
          }
        }
        return;
      }

      if (ctrl && e.shiftKey && e.key === "S") {
        e.preventDefault();
        const state = actions.getState();
        for (const tab of state.tabs) {
          if (tab.content !== tab.savedContent) {
            try {
              await invoke("write_file", { path: tab.path, contents: tab.content });
              actions.markSaved(tab.path);
            } catch (err) {
              toast.error(`Failed to save ${tab.name}: ${String(err)}`);
            }
          }
        }
        toast.success("All saved");
        return;
      }

      if (ctrl && e.key === "w") {
        e.preventDefault();
        const state = actions.getState();
        if (state.activeTabPath) {
          actions.closeTab(state.activeTabPath);
        }
        return;
      }

      // Ctrl+` - Toggle Terminal
      if (ctrl && e.key === "`") {
        e.preventDefault();
        onToggleTerminal();
        return;
      }

      // Ctrl+Shift+F - Search in Files
      if (ctrl && e.shiftKey && e.key === "F") {
        e.preventDefault();
        onSearchInFiles();
        return;
      }

      // Ctrl+G - Go to Line
      if (ctrl && e.key === "g") {
        e.preventDefault();
        onGoToLine();
        return;
      }

      // Ctrl+\ - Split Editor
      if (ctrl && e.key === "\\") {
        e.preventDefault();
        onSplitEditor();
        return;
      }
    };

    window.addEventListener("keydown", handler);
    return () => window.removeEventListener("keydown", handler);
  }, [onOpenCommandPalette, onOpenQuickOpen, onToggleTerminal, onSearchInFiles, onGoToLine, onSplitEditor]);
}
