import React, { useState, useEffect } from "react";
import { Dialog, DialogContent } from "@/components/ui/dialog";
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from "@/components/ui/command";
import { Upload, FileText, Settings, HelpCircle, Link } from "lucide-react";
import { useModal } from "@/context/ModalContext";
import { useAgentGraph } from "@/context/AgentGraphContext";

export function CommandPalette() {
  const [open, setOpen] = useState(false);
  const { openModal } = useModal();
  const { actions } = useAgentGraph();

  useEffect(() => {
    const down = (e: KeyboardEvent) => {
      if (e.key === "k" && (e.metaKey || e.ctrlKey)) {
        e.preventDefault();
        setOpen((open) => !open);
      }
    };

    document.addEventListener("keydown", down);
    return () => document.removeEventListener("keydown", down);
  }, []);

  const handleConnectObservability = () => {
    setOpen(false);
    openModal("observability-connection", "Connect to AI Observability");
  };

  const handleUploadTrace = () => {
    setOpen(false);
    actions.setActiveView("upload");
  };

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogContent className="overflow-hidden p-0 shadow-lg">
        <Command className="[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">
          <CommandInput placeholder="Type a command or search..." />
          <CommandList>
            <CommandEmpty>No results found.</CommandEmpty>

            <CommandGroup heading="Actions">
              <CommandItem onSelect={handleUploadTrace}>
                <Upload className="mr-2 h-4 w-4" />
                <span>Upload Trace</span>
              </CommandItem>
              <CommandItem onSelect={handleConnectObservability}>
                <Link className="mr-2 h-4 w-4" />
                <span>Connect to AI Observability</span>
              </CommandItem>

              <CommandItem>
                <FileText className="mr-2 h-4 w-4" />
                <span>View Traces</span>
              </CommandItem>
            </CommandGroup>

            <CommandGroup heading="Settings">
              <CommandItem>
                <Settings className="mr-2 h-4 w-4" />
                <span>Preferences</span>
              </CommandItem>
              <CommandItem>
                <HelpCircle className="mr-2 h-4 w-4" />
                <span>Help</span>
              </CommandItem>
            </CommandGroup>
          </CommandList>
        </Command>
      </DialogContent>
    </Dialog>
  );
}
