import { useCallback } from "react";
import { Command } from "cmdk";
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
import { VisuallyHidden } from "@radix-ui/react-visually-hidden";
import { actions, useStore } from "@/lib/store";
import { invoke } from "@tauri-apps/api/core";
import { open } from "@tauri-apps/plugin-dialog";
import { toast } from "sonner";

interface CommandPaletteProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onOpenSettings: () => void;
  onToggleTerminal: () => void;
  onSearchInFiles: () => void;
  onGoToLine: () => void;
  onSplitEditor: () => void;
}

const itemClass =
  "flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm text-foreground outline-none transition-colors aria-selected:bg-accent aria-selected:text-accent-foreground";

export function CommandPalette({
  open: isOpen,
  onOpenChange,
  onOpenSettings,
  onToggleTerminal,
  onSearchInFiles,
  onGoToLine,
  onSplitEditor,
}: CommandPaletteProps) {
  const store = useStore();
  const activeTab = store.tabs.find((t) => t.path === store.activeTabPath);

  const close = useCallback(() => onOpenChange(false), [onOpenChange]);

  const handleSave = useCallback(async () => {
    if (!activeTab) return;
    try {
      await invoke("write_file", { path: activeTab.path, contents: activeTab.content });
      actions.markSaved(activeTab.path);
      toast.success("File saved");
    } catch (err) {
      toast.error("Failed to save: " + String(err));
    }
    close();
  }, [activeTab, close]);

  const handleSaveAll = useCallback(async () => {
    for (const tab of store.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 files saved");
    close();
  }, [store.tabs, close]);

  const handleOpenFolder = useCallback(async () => {
    const selected = await open({ directory: true, multiple: false });
    if (selected) {
      actions.setWorkspace(selected as string);
    }
    close();
  }, [close]);

  return (
    <Dialog open={isOpen} onOpenChange={onOpenChange}>
      <DialogContent className="p-0 gap-0 max-w-[500px] overflow-hidden border-border">
        <VisuallyHidden>
          <DialogTitle>Command Palette</DialogTitle>
        </VisuallyHidden>
        <Command className="bg-card" loop>
          <Command.Input
            placeholder="Type a command..."
            className="h-10 w-full border-b border-border bg-transparent px-3 text-sm text-foreground outline-none placeholder:text-muted-foreground"
          />
          <Command.List className="max-h-[300px] overflow-y-auto p-1">
            <Command.Empty className="py-6 text-center text-sm text-muted-foreground">
              No commands found.
            </Command.Empty>

            <Command.Group heading="File">
              <Command.Item className={itemClass} onSelect={handleOpenFolder}>
                Open Folder
              </Command.Item>
              <Command.Item className={itemClass} onSelect={handleSave}>
                Save File
              </Command.Item>
              <Command.Item className={itemClass} onSelect={handleSaveAll}>
                Save All
              </Command.Item>
              <Command.Item
                className={itemClass}
                onSelect={() => {
                  if (activeTab) actions.closeTab(activeTab.path);
                  close();
                }}
              >
                Close Tab
              </Command.Item>
            </Command.Group>

            <Command.Group heading="View">
              <Command.Item
                className={itemClass}
                onSelect={() => {
                  actions.toggleSidebar();
                  close();
                }}
              >
                Toggle Sidebar
              </Command.Item>
              <Command.Item
                className={itemClass}
                onSelect={() => {
                  onToggleTerminal();
                  close();
                }}
              >
                Toggle Terminal
              </Command.Item>
              <Command.Item
                className={itemClass}
                onSelect={() => {
                  onSplitEditor();
                  close();
                }}
              >
                Split Editor
              </Command.Item>
              <Command.Item
                className={itemClass}
                onSelect={() => {
                  actions.updateSettings({
                    theme: store.settings.theme === "dark" ? "light" : "dark",
                  });
                  close();
                }}
              >
                Toggle Theme
              </Command.Item>
            </Command.Group>

            <Command.Group heading="Go">
              <Command.Item
                className={itemClass}
                onSelect={() => {
                  onGoToLine();
                  close();
                }}
              >
                Go to Line
              </Command.Item>
              <Command.Item
                className={itemClass}
                onSelect={() => {
                  onSearchInFiles();
                  close();
                }}
              >
                Search in Files
              </Command.Item>
            </Command.Group>

            <Command.Group heading="Settings">
              <Command.Item
                className={itemClass}
                onSelect={() => {
                  onOpenSettings();
                  close();
                }}
              >
                Open Settings
              </Command.Item>
            </Command.Group>
          </Command.List>
        </Command>
      </DialogContent>
    </Dialog>
  );
}
