"use client";

import * as React from "react";
import { useRouter } from "next/navigation";
import { Command as CommandPrimitive } from "cmdk";
import {
  ClipboardText,
  Buildings,
  SquaresFour,
  Presentation,
  MagnifyingGlass,
  GearSix,
  Users,
  Wallet,
  type Icon,
} from '@/lib/icons';

import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
import { cn } from "@/lib/utils";

const Command = React.forwardRef<
  React.ElementRef<typeof CommandPrimitive>,
  React.ComponentPropsWithoutRef<typeof CommandPrimitive>
>(({ className, ...props }, ref) => (
  <CommandPrimitive
    ref={ref}
    className={cn(
      "bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-xl",
      className,
    )}
    {...props}
  />
));
Command.displayName = CommandPrimitive.displayName;

type NavItem = { title: string; url: string; icon: Icon };

const NAV_ITEMS: NavItem[] = [
  { title: "Genel Bakış", url: "/dashboard", icon: SquaresFour },
  { title: "İlanlar", url: "/properties", icon: Buildings },
  { title: "Müşteriler", url: "/customers", icon: Users },
  { title: "Yatırımcılar", url: "/investors", icon: Wallet },
  { title: "Sunumlar", url: "/presentations", icon: Presentation },
  { title: "Aktiviteler", url: "/activities", icon: ClipboardText },
  { title: "Ofis Ayarları", url: "/settings/workspace", icon: GearSix },
];

export function CommandSearch() {
  const [open, setOpen] = React.useState(false);
  const [query, setQuery] = React.useState("");
  const router = useRouter();

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

  const filtered = query
    ? NAV_ITEMS.filter((item) => item.title.toLowerCase().includes(query.toLowerCase()))
    : NAV_ITEMS;

  return (
    <>
      <button
        onClick={() => setOpen(true)}
        className="bg-muted text-muted-foreground flex items-center gap-2 rounded-md px-3 py-1.5 text-sm"
      >
        <MagnifyingGlass className="size-3.5" />
        <span>Ara...</span>
        <kbd className="bg-background rounded border px-1 text-xs">⌘K</kbd>
      </button>

      <Dialog open={open} onOpenChange={setOpen}>
        <DialogContent className="overflow-hidden p-0">
          <DialogTitle className="sr-only">Arama</DialogTitle>
          <Command>
            <div className="flex items-center border-b px-3">
              <MagnifyingGlass className="mr-2 size-4 shrink-0 opacity-50" />
              <input
                value={query}
                onChange={(e) => setQuery(e.target.value)}
                placeholder="Sayfa ara..."
                className="placeholder:text-muted-foreground flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none"
              />
            </div>
            <div className="max-h-72 overflow-y-auto p-2">
              {filtered.map((item) => (
                <button
                  key={item.url}
                  onClick={() => { router.push(item.url); setOpen(false); setQuery(""); }}
                  className="hover:bg-accent flex w-full items-center gap-3 rounded-md px-3 py-2 text-sm"
                >
                  <item.icon className="size-4 opacity-60" />
                  {item.title}
                </button>
              ))}
            </div>
          </Command>
        </DialogContent>
      </Dialog>
    </>
  );
}
