"use client";

import { useEffect, useState, useCallback } from "react";
import { useRouter } from "next/navigation";
import { Command } from "cmdk";
import {
  LayoutDashboard,
  CreditCard,
  Users,
  CalendarDays,
  BarChart3,
  Settings,
  Upload,
  UserPlus,
  FileText,
  Search,
  BookOpen,
  LifeBuoy,
} from "lucide-react";
import { openContactSupport } from "@/components/support/contact-support-dialog";

const navItems = [
  { label: "Dashboard", href: "/", icon: LayoutDashboard, group: "Navigate" },
  { label: "Response Cards", href: "/cards", icon: CreditCard, group: "Navigate" },
  { label: "People", href: "/people", icon: Users, group: "Navigate" },
  { label: "Collection Days", href: "/events", icon: CalendarDays, group: "Navigate" },
  { label: "Reports", href: "/reports", icon: BarChart3, group: "Navigate" },
  { label: "Settings", href: "/settings", icon: Settings, group: "Navigate" },
  { label: "Form Templates", href: "/settings/form-templates", icon: FileText, group: "Navigate" },
  { label: "Help Center", href: "/docs", icon: BookOpen, group: "Navigate" },
];

const actionItems = [
  { label: "Upload Documents", icon: Upload, group: "Actions", action: "upload" },
  { label: "Create Person", icon: UserPlus, group: "Actions", action: "create-person" },
  { label: "Contact Support", icon: LifeBuoy, group: "Actions", action: "contact-support" },
];

export function CommandPalette() {
  const [open, setOpen] = useState(false);
  const router = useRouter();

  useEffect(() => {
    function onKeyDown(e: KeyboardEvent) {
      if (e.key === "k" && (e.metaKey || e.ctrlKey)) {
        e.preventDefault();
        setOpen((prev) => !prev);
      }
    }
    document.addEventListener("keydown", onKeyDown);
    return () => document.removeEventListener("keydown", onKeyDown);
  }, []);

  const runAction = useCallback(
    (action: string) => {
      setOpen(false);
      if (action === "upload") {
        window.dispatchEvent(new CustomEvent("open-upload-modal"));
      } else if (action === "create-person") {
        router.push("/people?new=true");
      } else if (action === "contact-support") {
        openContactSupport();
      }
    },
    [router]
  );

  const navigate = useCallback(
    (href: string) => {
      setOpen(false);
      router.push(href);
    },
    [router]
  );

  if (!open) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-start justify-center pt-[20vh]">
      <div
        className="fixed inset-0 bg-black/40 backdrop-blur-sm"
        onClick={() => setOpen(false)}
      />
      <Command
        className="relative w-full max-w-lg overflow-hidden rounded-2xl border border-border/60 bg-background/95 shadow-2xl backdrop-blur-xl"
        loop
      >
        <div className="flex items-center gap-2 border-b border-border/40 px-4">
          <Search className="size-4 shrink-0 text-muted-foreground" />
          <Command.Input
            placeholder="Type a command or search…"
            className="h-12 w-full bg-transparent text-sm outline-none placeholder:text-muted-foreground"
            autoFocus
          />
          <kbd className="hidden shrink-0 rounded-md border border-border/60 bg-muted/50 px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground sm:inline-block">
            ESC
          </kbd>
        </div>

        <Command.List className="max-h-80 overflow-y-auto p-2">
          <Command.Empty className="px-4 py-8 text-center text-sm text-muted-foreground">
            No results found.
          </Command.Empty>

          <Command.Group
            heading="Navigate"
            className="[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground"
          >
            {navItems.map((item) => (
              <Command.Item
                key={item.href}
                value={item.label}
                onSelect={() => navigate(item.href)}
                className="flex cursor-pointer items-center gap-3 rounded-lg px-3 py-2.5 text-sm text-foreground data-[selected=true]:bg-accent/60"
              >
                <item.icon className="size-4 text-muted-foreground" />
                {item.label}
              </Command.Item>
            ))}
          </Command.Group>

          <Command.Separator className="my-1 h-px bg-border/40" />

          <Command.Group
            heading="Actions"
            className="[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground"
          >
            {actionItems.map((item) => (
              <Command.Item
                key={item.action}
                value={item.label}
                onSelect={() => runAction(item.action)}
                className="flex cursor-pointer items-center gap-3 rounded-lg px-3 py-2.5 text-sm text-foreground data-[selected=true]:bg-accent/60"
              >
                <item.icon className="size-4 text-muted-foreground" />
                {item.label}
              </Command.Item>
            ))}
          </Command.Group>
        </Command.List>

        <div className="border-t border-border/40 px-4 py-2">
          <p className="text-[11px] text-muted-foreground">
            <kbd className="rounded border border-border/60 bg-muted/50 px-1 py-0.5 text-[10px] font-medium">↑↓</kbd>{" "}
            navigate{" "}
            <kbd className="ml-2 rounded border border-border/60 bg-muted/50 px-1 py-0.5 text-[10px] font-medium">↵</kbd>{" "}
            select{" "}
            <kbd className="ml-2 rounded border border-border/60 bg-muted/50 px-1 py-0.5 text-[10px] font-medium">esc</kbd>{" "}
            close
          </p>
        </div>
      </Command>
    </div>
  );
}
