"use client"

import { useState, useSyncExternalStore, useEffect, useMemo, useCallback } from "react"
import { useLocale, useTranslations } from "next-intl"
import { SearchIcon } from "lucide-react"

import { useRouter } from "@/i18n/navigation"
import { useAuth } from "@/app/providers/auth-provider"
import { getNavItemsByGroup } from "@/lib/acl-routes"
import { getNavIcon } from "@/lib/nav-icons"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import {
  CommandDialog,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
  CommandShortcut,
} from "@/components/ui/command"

export function GlobalSearch() {
  const router = useRouter()
  const locale = useLocale()
  const tNav = useTranslations("Nav")
  const tSearch = useTranslations("Search")
  const { hasPermission } = useAuth()

  const [open, setOpen] = useState(false)

  // Detect platform to render the correct modifier hint (⌘ vs Ctrl).
  // useSyncExternalStore keeps the server snapshot stable (false) to avoid a
  // hydration mismatch, then resolves on the client after mount.
  const isMac = useSyncExternalStore(
    () => () => {},
    () => /mac|iphone|ipad|ipod/i.test(navigator.platform),
    () => false
  )

  // Open on ⌘K / Ctrl+K (and ignore the shortcut while typing in a field).
  useEffect(() => {
    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key.toLowerCase() === "k" && (event.metaKey || event.ctrlKey)) {
        event.preventDefault()
        setOpen((prev) => !prev)
      }
    }
    document.addEventListener("keydown", onKeyDown)
    return () => document.removeEventListener("keydown", onKeyDown)
  }, [])

  // Only the groups/items the current user is allowed to see.
  const groups = useMemo(() => {
    return getNavItemsByGroup()
      .map((group) => ({
        groupKey: group.groupKey,
        label: tNav(group.navKey),
        items: group.items
          .filter((item) => hasPermission(item.listPermission))
          .map((item) => ({
            href: item.href,
            navKey: item.navKey,
            label: tNav(item.navKey),
            icon: getNavIcon(item.navKey),
          })),
      }))
      .filter((group) => group.items.length > 0)
  }, [tNav, hasPermission])

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

  return (
    <>
      <Button
        variant="outline"
        size="sm"
        onClick={() => setOpen(true)}
        className={cn(
          "relative justify-start gap-2 px-0 sm:px-3 w-9 sm:w-56 h-9 text-muted-foreground",
          "font-normal"
        )}
      >
        <SearchIcon className="size-4 shrink-0" />
        <span className="hidden sm:inline-flex">{tSearch("placeholder")}</span>
        <kbd className="hidden sm:inline-flex items-center gap-1 bg-muted ms-auto px-1.5 border rounded h-5 font-mono font-medium text-[10px] text-muted-foreground pointer-events-none select-none">
          {isMac ? "⌘" : "Ctrl"} K
        </kbd>
      </Button>

      <CommandDialog
        open={open}
        onOpenChange={setOpen}
        title={tSearch("title")}
        description={tSearch("description")}
      >
        <CommandInput placeholder={tSearch("inputPlaceholder")} />
        <CommandList>
          <CommandEmpty>{tSearch("empty")}</CommandEmpty>
          {groups.map((group) => (
            <CommandGroup key={group.groupKey} heading={group.label}>
              {group.items.map((item) => (
                <CommandItem
                  key={item.href}
                  // Filter on label + key + path so it matches in either language.
                  value={`${item.label} ${item.navKey} ${item.href}`}
                  onSelect={() => onSelect(item.href)}
                  dir={locale === "ar" ? "rtl" : "ltr"}
                >
                  {item.icon}
                  <span>{item.label}</span>
                  <CommandShortcut>{group.label}</CommandShortcut>
                </CommandItem>
              ))}
            </CommandGroup>
          ))}
        </CommandList>
      </CommandDialog>
    </>
  )
}
