import { open } from "@tauri-apps/plugin-dialog";
import { invoke } from "@tauri-apps/api/core";
import {
  Menubar as MenubarRoot,
  MenubarMenu,
  MenubarTrigger,
  MenubarContent,
  MenubarItem,
  MenubarSeparator,
  MenubarShortcut,
  MenubarSub,
  MenubarSubTrigger,
  MenubarSubContent,
} from "@/components/ui/menubar";
import { actions, useStore } from "@/lib/store";
import { toast } from "sonner";

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

export function AppMenubar({
  onOpenCommandPalette,
  onOpenQuickOpen,
  onOpenSettings,
  onToggleTerminal,
  onSearchInFiles,
  onGoToLine,
  onSplitEditor,
}: MenubarProps) {
  const store = useStore();
  const activeTab = store.tabs.find((t) => t.path === store.activeTabPath);

  const handleSave = 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));
    }
  };

  const handleSaveAll = 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");
  };

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

  return (
    <MenubarRoot>
      <MenubarMenu>
        <MenubarTrigger>File</MenubarTrigger>
        <MenubarContent>
          <MenubarItem onClick={handleOpenFolder}>
            Open Folder
          </MenubarItem>
          {store.recentWorkspaces.length > 0 && (
            <MenubarSub>
              <MenubarSubTrigger>Open Recent</MenubarSubTrigger>
              <MenubarSubContent>
                {store.recentWorkspaces.slice(0, 5).map((path) => {
                  const name = path.split("/").pop() ?? path.split("\\").pop() ?? path;
                  return (
                    <MenubarItem key={path} onClick={() => actions.setWorkspace(path)}>
                      {name}
                    </MenubarItem>
                  );
                })}
              </MenubarSubContent>
            </MenubarSub>
          )}
          <MenubarSeparator />
          <MenubarItem onClick={handleSave} disabled={!activeTab}>
            Save <MenubarShortcut>Ctrl+S</MenubarShortcut>
          </MenubarItem>
          <MenubarItem onClick={handleSaveAll}>
            Save All <MenubarShortcut>Ctrl+Shift+S</MenubarShortcut>
          </MenubarItem>
          <MenubarSeparator />
          <MenubarItem onClick={() => activeTab && actions.closeTab(activeTab.path)} disabled={!activeTab}>
            Close Tab <MenubarShortcut>Ctrl+W</MenubarShortcut>
          </MenubarItem>
        </MenubarContent>
      </MenubarMenu>

      <MenubarMenu>
        <MenubarTrigger>Edit</MenubarTrigger>
        <MenubarContent>
          <MenubarItem onClick={() => document.execCommand("undo")}>
            Undo <MenubarShortcut>Ctrl+Z</MenubarShortcut>
          </MenubarItem>
          <MenubarItem onClick={() => document.execCommand("redo")}>
            Redo <MenubarShortcut>Ctrl+Shift+Z</MenubarShortcut>
          </MenubarItem>
          <MenubarSeparator />
          <MenubarItem onClick={() => document.execCommand("cut")}>
            Cut <MenubarShortcut>Ctrl+X</MenubarShortcut>
          </MenubarItem>
          <MenubarItem onClick={() => document.execCommand("copy")}>
            Copy <MenubarShortcut>Ctrl+C</MenubarShortcut>
          </MenubarItem>
          <MenubarItem onClick={() => document.execCommand("paste")}>
            Paste <MenubarShortcut>Ctrl+V</MenubarShortcut>
          </MenubarItem>
          <MenubarSeparator />
          <MenubarItem onClick={onOpenQuickOpen}>
            Find File <MenubarShortcut>Ctrl+P</MenubarShortcut>
          </MenubarItem>
          <MenubarItem onClick={onSearchInFiles}>
            Search in Files <MenubarShortcut>Ctrl+Shift+F</MenubarShortcut>
          </MenubarItem>
          <MenubarItem onClick={onGoToLine} disabled={!activeTab}>
            Go to Line <MenubarShortcut>Ctrl+G</MenubarShortcut>
          </MenubarItem>
        </MenubarContent>
      </MenubarMenu>

      <MenubarMenu>
        <MenubarTrigger>View</MenubarTrigger>
        <MenubarContent>
          <MenubarItem onClick={() => actions.toggleSidebar()}>
            Toggle Sidebar <MenubarShortcut>Ctrl+B</MenubarShortcut>
          </MenubarItem>
          <MenubarItem onClick={onToggleTerminal}>
            Toggle Terminal <MenubarShortcut>Ctrl+`</MenubarShortcut>
          </MenubarItem>
          <MenubarItem onClick={onSplitEditor} disabled={!activeTab}>
            Split Editor <MenubarShortcut>Ctrl+\</MenubarShortcut>
          </MenubarItem>
          <MenubarSeparator />
          <MenubarItem onClick={onOpenCommandPalette}>
            Command Palette <MenubarShortcut>Ctrl+Shift+P</MenubarShortcut>
          </MenubarItem>
          <MenubarSeparator />
          <MenubarSub>
            <MenubarSubTrigger>Theme</MenubarSubTrigger>
            <MenubarSubContent>
              <MenubarItem onClick={() => actions.updateSettings({ theme: "dark" })}>
                Dark
              </MenubarItem>
              <MenubarItem onClick={() => actions.updateSettings({ theme: "light" })}>
                Light
              </MenubarItem>
            </MenubarSubContent>
          </MenubarSub>
        </MenubarContent>
      </MenubarMenu>

      <MenubarMenu>
        <MenubarTrigger>Help</MenubarTrigger>
        <MenubarContent>
          <MenubarItem onClick={onOpenSettings}>
            Settings
          </MenubarItem>
          <MenubarSeparator />
          <MenubarItem disabled>
            About Lunar Code
          </MenubarItem>
        </MenubarContent>
      </MenubarMenu>
    </MenubarRoot>
  );
}
