"use client";

import * as React from "react";
import { useRouter } from "next/navigation";
import { Command as CommandPrimitive } from "cmdk";
import {
  Briefcase,
  Calendar as CalendarIcon,
  CheckSquare,
  CircleDollarSign,
  FilePlus,
  LayoutDashboard,
  Loader2,
  Package,
  Receipt,
  Search,
  Settings,
  UserPlus,
  Users,
  Wallet,
  type LucideIcon,
} from "lucide-react";

import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
import { cn } from "@/lib/utils";
import {
  globalSearchAction,
  type SearchGroup,
  type SearchHit,
  type SearchResults,
} from "@/lib/appwrite/search-actions";

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}
    shouldFilter={false}
  />
));
Command.displayName = CommandPrimitive.displayName;

const CommandInput = React.forwardRef<
  React.ElementRef<typeof CommandPrimitive.Input>,
  React.ComponentPropsWithoutRef<typeof CommandPrimitive.Input>
>(({ className, ...props }, ref) => (
  <div className="flex items-center border-b px-4">
    <Search className="text-muted-foreground mr-2 size-4" />
    <CommandPrimitive.Input
      ref={ref}
      className={cn(
        "placeholder:text-muted-foreground flex h-12 w-full border-none bg-transparent py-3 text-base outline-none",
        className,
      )}
      {...props}
    />
  </div>
));
CommandInput.displayName = CommandPrimitive.Input.displayName;

const CommandList = React.forwardRef<
  React.ElementRef<typeof CommandPrimitive.List>,
  React.ComponentPropsWithoutRef<typeof CommandPrimitive.List>
>(({ className, ...props }, ref) => (
  <CommandPrimitive.List
    ref={ref}
    className={cn("max-h-[440px] overflow-y-auto overflow-x-hidden p-2", className)}
    {...props}
  />
));
CommandList.displayName = CommandPrimitive.List.displayName;

const CommandEmpty = React.forwardRef<
  React.ElementRef<typeof CommandPrimitive.Empty>,
  React.ComponentPropsWithoutRef<typeof CommandPrimitive.Empty>
>((props, ref) => (
  <CommandPrimitive.Empty
    ref={ref}
    className="text-muted-foreground py-8 text-center text-sm"
    {...props}
  />
));
CommandEmpty.displayName = CommandPrimitive.Empty.displayName;

const CommandGroup = React.forwardRef<
  React.ElementRef<typeof CommandPrimitive.Group>,
  React.ComponentPropsWithoutRef<typeof CommandPrimitive.Group>
>(({ className, ...props }, ref) => (
  <CommandPrimitive.Group
    ref={ref}
    className={cn(
      "overflow-hidden [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&:not(:first-child)]:mt-2",
      className,
    )}
    {...props}
  />
));
CommandGroup.displayName = CommandPrimitive.Group.displayName;

const CommandItem = React.forwardRef<
  React.ElementRef<typeof CommandPrimitive.Item>,
  React.ComponentPropsWithoutRef<typeof CommandPrimitive.Item>
>(({ className, ...props }, ref) => (
  <CommandPrimitive.Item
    ref={ref}
    className={cn(
      "data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground relative flex cursor-pointer select-none items-center gap-2 rounded-md px-3 py-2 text-sm outline-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50",
      className,
    )}
    {...props}
  />
));
CommandItem.displayName = CommandPrimitive.Item.displayName;

type NavItem = { key: string; title: string; url: string; icon: LucideIcon };

const NAV: NavItem[] = [
  { key: "nav-dashboard", title: "Genel bakış", url: "/dashboard", icon: LayoutDashboard },
  { key: "nav-customers", title: "Müşteriler", url: "/customers", icon: Users },
  { key: "nav-services", title: "Hizmetler", url: "/services", icon: Briefcase },
  { key: "nav-software", title: "Yazılımlarımız", url: "/software", icon: Package },
  { key: "nav-calendar", title: "Takvim", url: "/calendar", icon: CalendarIcon },
  { key: "nav-tasks", title: "Görevler", url: "/tasks", icon: CheckSquare },
  { key: "nav-finance", title: "Gelir / Gider", url: "/finance", icon: Wallet },
  { key: "nav-invoices", title: "Faturalar", url: "/invoices", icon: Receipt },
];

const QUICK_ACTIONS: NavItem[] = [
  { key: "qa-customer", title: "Yeni müşteri ekle", url: "/customers", icon: UserPlus },
  { key: "qa-invoice", title: "Yeni fatura kes", url: "/invoices", icon: Receipt },
  { key: "qa-task", title: "Yeni görev oluştur", url: "/tasks", icon: FilePlus },
  { key: "qa-event", title: "Takvime etkinlik ekle", url: "/calendar", icon: CalendarIcon },
  { key: "qa-finance", title: "Yeni gelir/gider girişi", url: "/finance", icon: CircleDollarSign },
];

const SETTINGS_NAV: NavItem[] = [
  { key: "set-workspace", title: "Şirket bilgileri", url: "/settings/workspace", icon: Settings },
  { key: "set-members", title: "Ekip üyeleri", url: "/settings/members", icon: Users },
  { key: "set-account", title: "Profil", url: "/settings/account", icon: Settings },
];

const GROUP_LABEL: Record<SearchGroup, string> = {
  customers: "Müşteriler",
  invoices: "Faturalar",
  tasks: "Görevler",
  services: "Hizmetler",
  software: "Yazılımlar",
  events: "Takvim",
  finance: "Finans",
};

const GROUP_ICON: Record<SearchGroup, LucideIcon> = {
  customers: Users,
  invoices: Receipt,
  tasks: CheckSquare,
  services: Briefcase,
  software: Package,
  events: CalendarIcon,
  finance: Wallet,
};

const GROUP_ORDER: SearchGroup[] = [
  "customers",
  "invoices",
  "tasks",
  "events",
  "finance",
  "services",
  "software",
];

interface CommandSearchProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

function filterNav(items: NavItem[], q: string): NavItem[] {
  if (!q) return items;
  const lower = q.toLocaleLowerCase("tr-TR");
  return items.filter((i) => i.title.toLocaleLowerCase("tr-TR").includes(lower));
}

export function CommandSearch({ open, onOpenChange }: CommandSearchProps) {
  const router = useRouter();
  const [query, setQuery] = React.useState("");
  const [results, setResults] = React.useState<SearchResults | null>(null);
  const [loading, setLoading] = React.useState(false);

  React.useEffect(() => {
    if (!open) {
      setQuery("");
      setResults(null);
      setLoading(false);
    }
  }, [open]);

  React.useEffect(() => {
    const trimmed = query.trim();
    if (trimmed.length < 2) {
      setResults(null);
      setLoading(false);
      return;
    }
    setLoading(true);
    const t = setTimeout(async () => {
      try {
        const r = await globalSearchAction(trimmed);
        setResults(r);
      } catch {
        setResults(null);
      } finally {
        setLoading(false);
      }
    }, 220);
    return () => clearTimeout(t);
  }, [query]);

  const handleSelect = (url: string) => {
    router.push(url);
    onOpenChange(false);
  };

  const navMatches = filterNav(NAV, query);
  const quickMatches = filterNav(QUICK_ACTIONS, query);
  const settingsMatches = filterNav(SETTINGS_NAV, query);

  const totalEntityHits = results
    ? GROUP_ORDER.reduce((s, g) => s + results[g].length, 0)
    : 0;

  const showEmpty =
    query.trim().length >= 2 &&
    !loading &&
    totalEntityHits === 0 &&
    navMatches.length === 0 &&
    quickMatches.length === 0 &&
    settingsMatches.length === 0;

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-[640px] overflow-hidden border p-0 shadow-2xl">
        <DialogTitle className="sr-only">Arama</DialogTitle>
        <Command>
          <CommandInput
            placeholder="Arayın: müşteri, fatura, görev, etkinlik, hizmet..."
            value={query}
            onValueChange={setQuery}
            autoFocus
          />
          <CommandList>
            {loading && (
              <div className="text-muted-foreground flex items-center justify-center py-6 text-sm">
                <Loader2 className="mr-2 size-3.5 animate-spin" />
                Aranıyor...
              </div>
            )}

            {showEmpty && <CommandEmpty>Sonuç bulunamadı.</CommandEmpty>}

            {results &&
              !loading &&
              GROUP_ORDER.map((group) => {
                const hits = results[group];
                if (hits.length === 0) return null;
                const Icon = GROUP_ICON[group];
                return (
                  <CommandGroup key={group} heading={GROUP_LABEL[group]}>
                    {hits.map((h: SearchHit) => (
                      <CommandItem
                        key={`${group}-${h.id}`}
                        value={`${group}-${h.id}-${h.title}`}
                        onSelect={() => handleSelect(h.url)}
                      >
                        <Icon className="text-muted-foreground size-4" />
                        <div className="flex min-w-0 flex-1 flex-col">
                          <span className="truncate">{h.title}</span>
                          {h.subtitle && (
                            <span className="text-muted-foreground truncate text-xs">
                              {h.subtitle}
                            </span>
                          )}
                        </div>
                      </CommandItem>
                    ))}
                  </CommandGroup>
                );
              })}

            {navMatches.length > 0 && (
              <CommandGroup heading="Sayfalar">
                {navMatches.map((item) => {
                  const Icon = item.icon;
                  return (
                    <CommandItem
                      key={item.key}
                      value={item.key}
                      onSelect={() => handleSelect(item.url)}
                    >
                      <Icon className="text-muted-foreground size-4" />
                      {item.title}
                    </CommandItem>
                  );
                })}
              </CommandGroup>
            )}

            {quickMatches.length > 0 && (
              <CommandGroup heading="Hızlı aksiyonlar">
                {quickMatches.map((item) => {
                  const Icon = item.icon;
                  return (
                    <CommandItem
                      key={item.key}
                      value={item.key}
                      onSelect={() => handleSelect(item.url)}
                    >
                      <Icon className="text-muted-foreground size-4" />
                      {item.title}
                    </CommandItem>
                  );
                })}
              </CommandGroup>
            )}

            {settingsMatches.length > 0 && (
              <CommandGroup heading="Ayarlar">
                {settingsMatches.map((item) => {
                  const Icon = item.icon;
                  return (
                    <CommandItem
                      key={item.key}
                      value={item.key}
                      onSelect={() => handleSelect(item.url)}
                    >
                      <Icon className="text-muted-foreground size-4" />
                      {item.title}
                    </CommandItem>
                  );
                })}
              </CommandGroup>
            )}
          </CommandList>

          <div className="text-muted-foreground bg-muted/30 flex items-center justify-between gap-2 border-t px-4 py-2 text-[11px]">
            <span>↵ Aç &nbsp;·&nbsp; ↑↓ Gez &nbsp;·&nbsp; Esc Kapat</span>
            <kbd className="bg-background rounded border px-1.5 py-0.5 font-mono">⌘K</kbd>
          </div>
        </Command>
      </DialogContent>
    </Dialog>
  );
}

export function SearchTrigger({ onClick }: { onClick: () => void }) {
  return (
    <button
      onClick={onClick}
      className="border-input bg-background text-muted-foreground hover:bg-accent hover:text-accent-foreground focus-visible:ring-ring relative inline-flex h-8 w-full items-center justify-start gap-2 whitespace-nowrap rounded-md border px-3 py-1 text-sm font-medium shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 disabled:pointer-events-none disabled:opacity-50 sm:pr-12 md:w-44 lg:w-64"
    >
      <Search className="mr-1 h-3.5 w-3.5" />
      <span>Hızlı ara...</span>
      <kbd className="bg-muted pointer-events-none absolute right-1.5 top-1.5 hidden h-4 select-none items-center gap-1 rounded border px-1.5 font-mono text-[10px] font-medium opacity-100 sm:flex">
        <span className="text-xs">⌘</span>K
      </kbd>
    </button>
  );
}
