"use client";

import { useCallback } from "react";
import { toast } from "sonner";

import { Icons } from "@turbostarter/ui-web/icons";
import {
  CommandDialog,
  CommandInput,
  CommandList,
  CommandEmpty,
  CommandGroup,
  CommandItem,
  CommandShortcut,
} from "@turbostarter/ui-web/command";

import { useGraphStore } from "../../stores/useGraphStore";
import { CONTAINER_TYPES } from "./DiagramCanvas";

interface CommandPaletteProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onToggleSidebar: () => void;
  onToggleRightPanel: () => void;
  onOpenRightPanel: () => void;
}

export function CommandPalette({
  open,
  onOpenChange,
  onToggleSidebar,
  onToggleRightPanel,
  onOpenRightPanel,
}: CommandPaletteProps) {
  const nodes = useGraphStore((s) => s.nodes);

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

  const handleFitView = useCallback(() => {
    close();
    useGraphStore.getState().requestFitView();
  }, [close]);

  const handleGoToNode = useCallback(
    (nodeId: string) => {
      close();
      useGraphStore.getState().setFocusNodeId(nodeId);
    },
    [close],
  );

  const handleToggleSidebar = useCallback(() => {
    close();
    onToggleSidebar();
  }, [close, onToggleSidebar]);

  const handleToggleChat = useCallback(() => {
    close();
    onToggleRightPanel();
  }, [close, onToggleRightPanel]);

  const handleAIAction = useCallback(
    (text: string) => {
      close();
      onOpenRightPanel();
      useGraphStore.getState().setPrefillChat("", text);
    },
    [close, onOpenRightPanel],
  );

  const handleExport = useCallback(() => {
    close();
    toast.info("Export coming soon", {
      description: "This feature is planned for a future release.",
    });
  }, [close]);

  const navigableNodes = nodes.filter(
    (n) => !CONTAINER_TYPES.has(n.type ?? ""),
  );

  return (
    <CommandDialog open={open} onOpenChange={onOpenChange}>
      <CommandInput placeholder="Type a command or search..." />
      <CommandList>
        <CommandEmpty>No results found.</CommandEmpty>

        <CommandGroup heading="AI Actions">
          <CommandItem onSelect={() => handleAIAction("Generate a diagram: ")}>
            <Icons.Sparkles className="size-4" />
            <span>Generate diagram from description</span>
          </CommandItem>
          <CommandItem onSelect={() => handleAIAction("Suggest improvements for this diagram")}>
            <Icons.Lightbulb className="size-4" />
            <span>Suggest improvements</span>
          </CommandItem>
          <CommandItem onSelect={() => handleAIAction("Analyze the semantics of this diagram")}>
            <Icons.Search className="size-4" />
            <span>Analyze diagram semantics</span>
          </CommandItem>
        </CommandGroup>

        <CommandGroup heading="Navigation">
          <CommandItem onSelect={handleFitView}>
            <Icons.Zap className="size-4" />
            <span>Fit to view</span>
          </CommandItem>
          <CommandItem onSelect={handleToggleSidebar}>
            <Icons.PanelLeft className="size-4" />
            <span>Toggle sidebar</span>
            <CommandShortcut>⌘B</CommandShortcut>
          </CommandItem>
          <CommandItem onSelect={handleToggleChat}>
            <Icons.MessageSquare className="size-4" />
            <span>Toggle chat panel</span>
            <CommandShortcut>⌘J</CommandShortcut>
          </CommandItem>
        </CommandGroup>

        <CommandGroup heading="Diagram">
          <CommandItem onSelect={handleExport}>
            <Icons.Download className="size-4" />
            <span>Export as PNG</span>
          </CommandItem>
          <CommandItem onSelect={handleExport}>
            <Icons.Download className="size-4" />
            <span>Export as SVG</span>
          </CommandItem>
        </CommandGroup>

        {navigableNodes.length > 0 && (
          <CommandGroup heading="Go to Node">
            {navigableNodes.map((n) => (
              <CommandItem
                key={n.id}
                onSelect={() => handleGoToNode(n.id)}
              >
                <Icons.Circle className="size-4" />
                <span>
                  {(n.data as { label?: string }).label ?? n.id}
                </span>
              </CommandItem>
            ))}
          </CommandGroup>
        )}
      </CommandList>
    </CommandDialog>
  );
}
