import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useMemo, useRef, useState } from "react";
import { Check, ChevronDown, Loader2, UserRound, X } from "lucide-react";
import { Button } from "./button";
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, } from "./command";
import { Popover, PopoverContent, PopoverTrigger } from "./popover";
const DEFAULT_MIN_QUERY_LENGTH = 2;
export function UserPicker({ value, displayValue, disabled = false, placeholder = "Select user", buttonTestId, buttonClassName, popoverClassName = "w-[320px] p-0", inputClassName = "h-8 text-xs", inputPlaceholder = "Search users...", groupHeading = "Users", emptyMessage = "No users found", loadingMessage = "Searching users...", allowClear = false, clearLabel = "Clear user", showIcon = true, showChevron = true, minQueryLength = DEFAULT_MIN_QUERY_LENGTH, limit = 20, debounceMs = 250, searchUsers, onChange, }) {
    const [open, setOpen] = useState(false);
    const [query, setQuery] = useState("");
    const [loading, setLoading] = useState(false);
    const [results, setResults] = useState([]);
    const triggerRef = useRef(null);
    const [portalContainer, setPortalContainer] = useState(null);
    useEffect(() => {
        if (!open)
            return;
        const trimmed = query.trim();
        if (trimmed.length < minQueryLength) {
            setResults([]);
            setLoading(false);
            return;
        }
        let cancelled = false;
        const handle = window.setTimeout(async () => {
            setLoading(true);
            try {
                const next = await searchUsers(trimmed, limit);
                if (!cancelled)
                    setResults(next);
            }
            catch {
                if (!cancelled)
                    setResults([]);
            }
            finally {
                if (!cancelled)
                    setLoading(false);
            }
        }, debounceMs);
        return () => {
            cancelled = true;
            window.clearTimeout(handle);
        };
    }, [debounceMs, limit, minQueryLength, open, query, searchUsers]);
    const currentLabel = useMemo(() => {
        if (!value)
            return "";
        const fromResults = results.find((item) => item.userName.toLowerCase() === value.toLowerCase());
        return fromResults?.displayName || displayValue || value;
    }, [displayValue, results, value]);
    const canSearch = query.trim().length >= minQueryLength;
    const handleSelectUser = (next) => {
        onChange({
            userName: next.userName,
            displayName: next.displayName || next.userName,
            email: next.email ?? null,
        });
        setOpen(false);
    };
    return (_jsxs(Popover, { open: open, onOpenChange: (nextOpen) => {
            if (nextOpen && triggerRef.current) {
                const dialogContent = triggerRef.current.closest('[data-slot="dialog-content"]');
                setPortalContainer(dialogContent);
            }
            setOpen(nextOpen);
        }, enableIframeClickDetection: false, children: [_jsx(PopoverTrigger, { asChild: true, children: _jsxs(Button, { ref: triggerRef, size: "sm", variant: "outline", className: buttonClassName ||
                        "bg-neutral-grey-5 h-8 w-full justify-start rounded-md text-xs font-medium", disabled: disabled, "data-testid": buttonTestId, children: [showIcon ? (_jsx(UserRound, { className: "h-3.5 w-3.5 shrink-0 opacity-70", strokeWidth: 1.5 })) : null, _jsx("span", { className: "min-w-0 flex-1 truncate text-left", children: currentLabel || placeholder }), showChevron ? (_jsx(ChevronDown, { className: "ml-auto h-3.5 w-3.5 opacity-60" })) : null] }) }), _jsx(PopoverContent, { className: popoverClassName, align: "start", container: portalContainer, onMouseDown: (event) => event.stopPropagation(), onClick: (event) => event.stopPropagation(), children: _jsxs(Command, { shouldFilter: false, children: [_jsx(CommandInput, { value: query, onValueChange: setQuery, placeholder: inputPlaceholder, className: inputClassName, autoFocus: true }), _jsxs(CommandList, { className: "max-h-64", children: [!canSearch && (_jsx(CommandGroup, { children: _jsxs(CommandItem, { disabled: true, className: "text-muted-foreground", children: ["Type at least ", minQueryLength, " characters"] }) })), allowClear && value ? (_jsx(CommandGroup, { heading: "Current", children: _jsxs(CommandItem, { onSelect: () => {
                                            onChange(null);
                                            setOpen(false);
                                        }, children: [_jsx(X, { className: "h-3.5 w-3.5" }), _jsx("span", { children: clearLabel })] }) })) : null, canSearch && (_jsx(CommandGroup, { heading: groupHeading, children: loading ? (_jsxs(CommandItem, { disabled: true, children: [_jsx(Loader2, { className: "h-3.5 w-3.5 animate-spin" }), _jsx("span", { children: loadingMessage })] })) : (results.map((user) => (_jsxs(CommandItem, { value: user.userName, onSelect: () => handleSelectUser(user), children: [_jsx(UserRound, { className: "h-3.5 w-3.5", strokeWidth: 1.5 }), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsx("div", { className: "truncate", children: user.displayName || user.userName }), _jsxs("div", { className: "text-muted-foreground truncate text-[10px]", children: [user.userName, user.email ? ` | ${user.email}` : ""] })] }), value?.toLowerCase() === user.userName.toLowerCase() ? (_jsx(Check, { className: "h-3.5 w-3.5" })) : null] }, user.userName)))) })), canSearch && !loading && results.length === 0 ? (_jsx(CommandEmpty, { children: emptyMessage })) : null] })] }) })] }));
}
//# sourceMappingURL=UserPicker.js.map