import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useMemo, useRef, useState } from "react";
import { Check, ChevronDown, Loader2, UserRound } from "lucide-react";
import { Button } from "../../components/ui/button";
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, } from "../../components/ui/command";
import { Popover, PopoverContent, PopoverTrigger } from "../../components/ui/popover";
import { searchTaskAssignableUsers } from "../services/taskService";
const MIN_QUERY_LENGTH = 2;
export function ProjectExecutionUserPicker({ projectId, value, displayValue, disabled = false, placeholder = "Choose user", buttonTestId, 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 < MIN_QUERY_LENGTH) {
            setResults([]);
            return;
        }
        let cancelled = false;
        const handle = window.setTimeout(async () => {
            setLoading(true);
            try {
                const result = await searchTaskAssignableUsers(projectId, trimmed, 20);
                if (!cancelled) {
                    setResults(result.type === "success" ? (result.data ?? []) : []);
                }
            }
            finally {
                if (!cancelled)
                    setLoading(false);
            }
        }, 250);
        return () => {
            cancelled = true;
            window.clearTimeout(handle);
        };
    }, [open, projectId, query]);
    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 >= MIN_QUERY_LENGTH;
    const handleSelectUser = (next) => {
        onChange({
            userId: next.userName,
            displayName: next.displayName || next.userName,
        });
        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: "h-8 w-full justify-start rounded-md bg-gray-5 text-xs font-medium", disabled: disabled, "data-testid": buttonTestId, children: [_jsx(UserRound, { className: "h-3.5 w-3.5 shrink-0 opacity-70" }), _jsx("span", { className: "min-w-0 flex-1 truncate text-left", children: currentLabel || placeholder }), _jsx(ChevronDown, { className: "ml-auto h-3.5 w-3.5 opacity-60" })] }) }), _jsx(PopoverContent, { className: "w-[320px] p-0", 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: "Search users...", className: "h-8 text-xs", 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 ", MIN_QUERY_LENGTH, " characters"] }) })), canSearch && (_jsx(CommandGroup, { heading: "Users", children: loading ? (_jsxs(CommandItem, { disabled: true, children: [_jsx(Loader2, { className: "h-3.5 w-3.5 animate-spin" }), _jsx("span", { children: "Searching users..." })] })) : (results.map((user) => (_jsxs(CommandItem, { value: user.userName, onSelect: () => handleSelectUser(user), children: [_jsx(UserRound, { className: "h-3.5 w-3.5" }), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsx("div", { className: "truncate", children: user.displayName || user.userName }), _jsxs("div", { className: "truncate text-[10px] text-muted-foreground", 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: "No users found" })) : null] })] }) })] }));
}
//# sourceMappingURL=ProjectExecutionUserPicker.js.map