"use client"; import { useEffect, useRef, useState } from "react"; import type { Assignment, Media, Profile } from "@/payload-types"; import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"; import { Input } from "@/components/ui/input"; import { cn } from "@/lib/utils"; import { Loader2Icon, SearchIcon, XIcon } from "lucide-react"; export interface RecipientSelection { id: number; username: string; displayName?: string | null; profileId?: number; } interface RecipientPickerProps { selectedUsers: RecipientSelection[]; onSelect: (user: RecipientSelection) => void; onRemove: (id: number) => void; maxSelections?: number; disabled?: boolean; } interface SearchResult extends RecipientSelection { rankName?: string | null; insigniaUrl?: string | null; assignmentLabel?: string | null; } function initialsOf(username: string): string { return username.slice(0, 2).toUpperCase(); } /** * Searchable recipient picker. Queries the profiles REST API (users have no * `profile` relationship, so searching /api/users would not surface rank * data) and enriches each hit with the user's primary assignment. */ export function RecipientPicker({ selectedUsers, onSelect, onRemove, maxSelections, disabled = false, }: RecipientPickerProps) { const [query, setQuery] = useState(""); const [results, setResults] = useState([]); const [searching, setSearching] = useState(false); const [open, setOpen] = useState(false); const [activeIndex, setActiveIndex] = useState(0); const wrapperRef = useRef(null); const searchSeq = useRef(0); // Debounced search with a sequence guard so stale responses are dropped. useEffect(() => { const trimmed = query.trim(); if (trimmed.length < 1) { setResults([]); setSearching(false); return; } const seq = ++searchSeq.current; setSearching(true); const timer = setTimeout(async () => { try { const q = encodeURIComponent(trimmed); const url = `/api/profiles?where[or][0][user.username][like]=${q}&where[or][1][user.displayName][like]=${q}&limit=10&depth=2`; const res = await fetch(url, { cache: "no-store" }); if (!res.ok) throw new Error("Search failed"); const data = (await res.json()) as { docs?: unknown[] }; const mapped: SearchResult[] = []; for (const doc of data.docs ?? []) { const profile = doc as Profile; const userDoc = profile.user; if (typeof userDoc !== "object" || !userDoc) continue; const rank = typeof profile.rank === "object" && profile.rank ? profile.rank : null; mapped.push({ id: userDoc.id, username: userDoc.username, displayName: userDoc.displayName, profileId: profile.id, rankName: rank?.name ?? null, insigniaUrl: rank && typeof rank.insignia === "object" && rank.insignia ? (rank.insignia as Media).url : null, }); } // Enrich with each user's primary assignment (best-effort). const assignmentResults = await Promise.allSettled( mapped.map((r) => fetch(`/api/assignments?where[members][equals]=${r.id}&limit=1&depth=0`, { cache: "no-store", }) .then((res) => (res.ok ? res.json() : null)) .then((json) => { const doc = (json as { docs?: unknown[] } | null)?.docs?.[0]; if (!doc || typeof doc !== "object") return null; const assignment = doc as Assignment; return assignment.callsign ? `[${assignment.callsign}] ${assignment.name}` : assignment.name; }), ), ); assignmentResults.forEach((res, i) => { if (res.status === "fulfilled" && res.value) mapped[i].assignmentLabel = res.value; }); if (seq !== searchSeq.current) return; setResults(mapped); setActiveIndex(0); } catch { if (seq === searchSeq.current) { setResults([]); } } finally { if (seq === searchSeq.current) setSearching(false); } }, 300); return () => clearTimeout(timer); }, [query]); // Close the dropdown on outside click. useEffect(() => { if (!open) return; function handlePointerDown(e: MouseEvent) { if (wrapperRef.current && !wrapperRef.current.contains(e.target as Node)) { setOpen(false); } } document.addEventListener("mousedown", handlePointerDown); return () => document.removeEventListener("mousedown", handlePointerDown); }, [open]); function select(result: SearchResult) { onSelect({ id: result.id, username: result.username, displayName: result.displayName, profileId: result.profileId, }); setQuery(""); setActiveIndex(0); } const atMax = maxSelections != null && selectedUsers.length >= maxSelections; return (
{selectedUsers.length > 0 && (
{selectedUsers.map((u) => ( {initialsOf(u.username)} {u.displayName || u.username} @{u.username} ))}
)}
{ setQuery(e.target.value); setOpen(true); }} onFocus={() => setOpen(true)} onKeyDown={(e) => { if (e.key === "Escape") { setOpen(false); return; } if (!open || results.length === 0) return; if (e.key === "ArrowDown") { e.preventDefault(); setActiveIndex((i) => Math.min(i + 1, results.length - 1)); } else if (e.key === "ArrowUp") { e.preventDefault(); setActiveIndex((i) => Math.max(i - 1, 0)); } else if (e.key === "Enter") { e.preventDefault(); const active = results[activeIndex]; if (active) select(active); } }} placeholder={ atMax ? "Maximum recipients selected" : "Search by username or display name..." } className="pl-8" role="combobox" aria-expanded={open} aria-controls="recipient-picker-results" /> {open && query.trim().length > 0 && (
{searching ? (
Searching...
) : results.length === 0 ? (
No users found.
) : ( results.map((result, i) => { const alreadySelected = selectedUsers.some((u) => u.id === result.id); return ( ); }) )}
)}
); }