"use client"; import { useCallback, useEffect, useRef, useState } from "react"; import { useRouter } from "next/navigation"; import { CommandDialog, CommandInput, CommandList, CommandEmpty, CommandGroup, CommandItem, } from "@/components/ui/command"; import { Bell, Car, ClipboardCheck, FileText, Package, Settings, Users, Wrench } from "lucide-react"; import { globalSearch, getRecentCustomers } from "@/features/search/Actions/searchActions"; interface SearchResult { vehicles: { id: string; make: string; model: string; year: number; licensePlate: string | null; }[]; customers: { id: string; name: string; email: string | null; phone: string | null; company: string | null; vehicles: { id: string; make: string; model: string; year: number; licensePlate: string | null; }[]; }[]; services: { id: string; title: string; invoiceNumber: string | null; vehicle: { id: string; make: string; model: string; year: number; licensePlate: string | null; }; }[]; parts: { id: string; name: string; partNumber: string | null; quantity: number; }[]; quotes: { id: string; title: string; quoteNumber: string | null; status: string; }[]; reminders: { id: string; title: string; dueDate: Date | null; isCompleted: boolean; vehicle: { id: string; make: string; model: string; year: number; licensePlate: string | null; }; }[]; inspections: { id: string; status: string; createdAt: Date; template: { name: string }; vehicle: { id: string; make: string; model: string; year: number; licensePlate: string | null; }; }[]; } const SEARCHABLE_SETTINGS = [ { label: "Company", description: "Company, business, branding, logo", href: "/settings/company", keywords: ["company", "business", "branding", "logo", "name", "address"] }, { label: "Account", description: "Account, profile, password", href: "/settings/account", keywords: ["account", "profile", "password", "email", "2fa"] }, { label: "Team", description: "Team members and roles", href: "/settings/team", keywords: ["team", "members", "roles", "invite"] }, { label: "Invoice", description: "Invoice layout and prefix", href: "/settings/invoice", keywords: ["invoice", "layout", "prefix", "footer", "due"] }, { label: "Templates", description: "Invoice & quote template styling", href: "/settings/templates", keywords: ["template", "styling", "colors", "font", "header", "quote"] }, { label: "Payment", description: "Payment and bank settings", href: "/settings/payment", keywords: ["payment", "bank", "vipps", "stripe", "terms"] }, { label: "Currency", description: "Currency, tax, and VAT", href: "/settings/currency", keywords: ["currency", "tax", "vat", "unit"] }, { label: "Custom Fields", description: "Custom fields configuration", href: "/settings/custom-fields", keywords: ["custom fields", "fields"] }, { label: "Email", description: "Email and SMTP settings", href: "/settings/email", keywords: ["email", "mail", "smtp", "sending"] }, { label: "Workshop", description: "Workshop and labor settings", href: "/settings/workshop", keywords: ["workshop", "technician", "labor", "hours"] }, { label: "Appearance", description: "Theme and date settings", href: "/settings/appearance", keywords: ["appearance", "theme", "dark", "light", "date", "timezone"] }, { label: "Data", description: "Data export and backup", href: "/settings/data", keywords: ["data", "export", "import", "backup"] }, { label: "About", description: "Version and info", href: "/settings/about", keywords: ["about", "version", "info"] }, ]; function useDebounce(value: T, delay: number): T { const [debounced, setDebounced] = useState(value); useEffect(() => { const timer = setTimeout(() => setDebounced(value), delay); return () => clearTimeout(timer); }, [value, delay]); return debounced; } type RecentCustomer = { id: string; name: string; email: string | null; phone: string | null; company: string | null; }; function filterSettings(query: string) { const q = query.toLowerCase(); return SEARCHABLE_SETTINGS.filter( (s) => s.label.toLowerCase().includes(q) || s.description.toLowerCase().includes(q) || s.keywords.some((k) => k.toLowerCase().includes(q)) ); } export function SearchCommand() { const router = useRouter(); const [open, setOpen] = useState(false); const [query, setQuery] = useState(""); const [results, setResults] = useState({ vehicles: [], customers: [], services: [], parts: [], quotes: [], reminders: [], inspections: [] }); const [loading, setLoading] = useState(false); const [recentCustomers, setRecentCustomers] = useState([]); const recentFetchedRef = useRef(false); const debouncedQuery = useDebounce(query, 300); useEffect(() => { const down = (e: KeyboardEvent) => { if (e.key === "k" && (e.metaKey || e.ctrlKey)) { e.preventDefault(); setOpen((prev) => !prev); } }; document.addEventListener("keydown", down); return () => document.removeEventListener("keydown", down); }, []); // Fetch recent customers when dialog opens useEffect(() => { if (open && !recentFetchedRef.current) { recentFetchedRef.current = true; getRecentCustomers().then((res) => { if (res.success && res.data) { setRecentCustomers(res.data); } }); } if (!open) { recentFetchedRef.current = false; } }, [open]); useEffect(() => { if (!debouncedQuery || debouncedQuery.length < 2) { // eslint-disable-next-line react-hooks/set-state-in-effect -- clearing results on query change is intentional setResults({ vehicles: [], customers: [], services: [], parts: [], quotes: [], reminders: [], inspections: [] }); setLoading(false); return; } let cancelled = false; setLoading(true); globalSearch(debouncedQuery).then((res) => { if (cancelled) return; if (res.success && res.data) { setResults(res.data); } setLoading(false); }); return () => { cancelled = true; }; }, [debouncedQuery]); const handleSelect = useCallback( (path: string) => { setOpen(false); setQuery(""); router.push(path); }, [router] ); const hasQuery = debouncedQuery.length >= 2; const hasResults = results.vehicles.length > 0 || results.customers.length > 0 || results.services.length > 0 || results.parts.length > 0 || results.quotes.length > 0 || results.reminders.length > 0 || results.inspections.length > 0; const matchedSettings = hasQuery ? filterSettings(debouncedQuery) : SEARCHABLE_SETTINGS; const showDefault = !hasQuery; return ( {!loading && hasQuery && !hasResults && matchedSettings.length === 0 && ( No results found. )} {/* Default view: recent customers + all settings */} {showDefault && recentCustomers.length > 0 && ( {recentCustomers.map((c) => ( handleSelect(`/customers/${c.id}`)} >
{c.name} {[c.company, c.email, c.phone].filter(Boolean).join(" · ")}
))}
)} {/* Search results: grouped by entity type — kept visible while loading to avoid flicker */} {hasQuery && ( <> {results.customers.length > 0 && ( {results.customers.map((c) => (
handleSelect(`/customers/${c.id}`)} >
{c.name} {[c.company, c.email, c.phone].filter(Boolean).join(" · ")}
{c.vehicles.map((v) => ( handleSelect(`/vehicles/${v.id}`)} className="pl-10" > {v.year} {v.make} {v.model} {v.licensePlate && ( {v.licensePlate} )} ))}
))}
)} {results.vehicles.length > 0 && ( {results.vehicles.map((v) => ( handleSelect(`/vehicles/${v.id}`)} > {v.year} {v.make} {v.model} {v.licensePlate && ( {v.licensePlate} )} ))} )} {results.services.length > 0 && ( {results.services.map((s) => ( handleSelect(`/vehicles/${s.vehicle.id}/service/${s.id}`)} >
{s.title} {[ s.invoiceNumber, `${s.vehicle.year} ${s.vehicle.make} ${s.vehicle.model}`, s.vehicle.licensePlate, ].filter(Boolean).join(" · ")}
))}
)} {results.quotes.length > 0 && ( {results.quotes.map((q) => ( handleSelect(`/quotes/${q.id}`)} >
{q.title} {[q.quoteNumber, q.status].filter(Boolean).join(" · ")}
))}
)} {results.parts.length > 0 && ( {results.parts.map((p) => ( handleSelect("/inventory")} >
{p.name} {[p.partNumber, `${p.quantity} in stock`].filter(Boolean).join(" · ")}
))}
)} {results.reminders.length > 0 && ( {results.reminders.map((r) => ( handleSelect(`/vehicles/${r.vehicle.id}?tab=reminders`)} >
{r.title}{r.isCompleted && (done)} {`${r.vehicle.year} ${r.vehicle.make} ${r.vehicle.model}`} {r.vehicle.licensePlate && ` · ${r.vehicle.licensePlate}`}
))}
)} {results.inspections.length > 0 && ( {results.inspections.map((insp) => ( handleSelect(`/inspections/${insp.id}`)} >
{insp.template.name} {`${insp.vehicle.year} ${insp.vehicle.make} ${insp.vehicle.model}`} {insp.vehicle.licensePlate && ` · ${insp.vehicle.licensePlate}`} {` · ${insp.status}`}
))}
)} )} {/* Settings group: shown in both default and search views */} {matchedSettings.length > 0 && ( {matchedSettings.map((s) => ( handleSelect(s.href)} >
{s.label} {s.description}
))}
)}
ESC to close
); }