import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useMemo, useRef, useState } from "react";
import { Check, ChevronDown, Loader2, User, X } from "lucide-react";
import { useResolvedUser } from "../../editor/services/userResolution";
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, searchTemplateAssignableUsers, } from "../services/taskService";
import { getAiProfilesErrorMessage, loadAiProfiles, } from "../../editor/services/aiService";
import { AgentProfileIcon } from "../../agents-view/AgentProfileIcon";
import { LicenseFeatures, useFeature } from "../../licensing";
import { TaskAssigneeIcon } from "./TaskAssigneeBadge";
const MIN_QUERY_LENGTH = 2;
export function TaskAssigneePicker({ projectId, projectTemplateId, assigneeType = null, value, displayValue, disabled = false, onChange, placeholder = "Assign user or agent", buttonClassName, buttonTestId, showChevron = true, showAssigneeIcon = false, }) {
    const canUseAi = useFeature(LicenseFeatures.AI);
    const [open, setOpen] = useState(false);
    const [query, setQuery] = useState("");
    const [loading, setLoading] = useState(false);
    const [loadingProfiles, setLoadingProfiles] = useState(false);
    const [profilesError, setProfilesError] = useState(null);
    const [results, setResults] = useState([]);
    const [profiles, setProfiles] = 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 = projectTemplateId
                    ? await searchTemplateAssignableUsers(projectTemplateId, trimmed, 20)
                    : projectId
                        ? await searchTaskAssignableUsers(projectId, trimmed, 20)
                        : null;
                if (!cancelled) {
                    setResults(result?.type === "success" ? (result.data ?? []) : []);
                }
            }
            finally {
                if (!cancelled)
                    setLoading(false);
            }
        }, 250);
        return () => {
            cancelled = true;
            window.clearTimeout(handle);
        };
    }, [open, projectId, projectTemplateId, query]);
    useEffect(() => {
        if (!open)
            return;
        if (!canUseAi) {
            setProfiles([]);
            setProfilesError(null);
            setLoadingProfiles(false);
            return;
        }
        let cancelled = false;
        setLoadingProfiles(true);
        setProfilesError(null);
        loadAiProfiles()
            .then((items) => {
            if (cancelled)
                return;
            setProfiles(items || []);
        })
            .catch((error) => {
            if (cancelled)
                return;
            setProfiles([]);
            setProfilesError(getAiProfilesErrorMessage(error));
        })
            .finally(() => {
            if (!cancelled)
                setLoadingProfiles(false);
        });
        return () => {
            cancelled = true;
        };
    }, [canUseAi, open]);
    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 resolvedUserAssignee = useResolvedUser(assigneeType === "user" && value ? value : null, { fullName: currentLabel || displayValue || null });
    const currentAssigneeLabel = assigneeType === "user" && value
        ? resolvedUserAssignee.displayName
        : currentLabel;
    const handleSelectUser = (next) => {
        onChange({
            assigneeType: "user",
            assigneeId: next.userName,
            displayName: next.displayName || next.userName,
            description: next.email || null,
        });
        setOpen(false);
    };
    const handleSelectProfile = (profile) => {
        onChange({
            assigneeType: "Agent",
            assigneeId: profile.id,
            displayName: profile.displayTitle || profile.name,
            description: profile.description || null,
        });
        setOpen(false);
    };
    const canSearch = query.trim().length >= MIN_QUERY_LENGTH;
    const normalizedQuery = query.trim().toLowerCase();
    const filteredProfiles = useMemo(() => {
        if (!canUseAi)
            return [];
        if (!normalizedQuery)
            return profiles;
        return profiles.filter((profile) => {
            const title = (profile.displayTitle || profile.name || "").toLowerCase();
            const desc = (profile.description || "").toLowerCase();
            return (title.includes(normalizedQuery) ||
                desc.includes(normalizedQuery) ||
                profile.id.toLowerCase().includes(normalizedQuery));
        });
    }, [canUseAi, profiles, normalizedQuery]);
    const assigneeIcon = _jsx(TaskAssigneeIcon, { assigneeType: assigneeType });
    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 ||
                        "h-8 min-h-0 w-[220px] justify-between rounded-md bg-white text-xs font-medium", disabled: disabled, "data-testid": buttonTestId, children: [showAssigneeIcon ? assigneeIcon : null, _jsx("span", { className: "truncate text-left", children: currentAssigneeLabel || placeholder }), showChevron ? (_jsx(ChevronDown, { className: "h-3.5 w-3.5 text-neutral-grey-100" })) : null] }) }), _jsx(PopoverContent, { className: "w-[300px] 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 or agent profiles...", className: "h-8 text-xs", autoFocus: true }), _jsxs(CommandList, { className: "max-h-64", children: [!value && !canSearch && (_jsx(CommandGroup, { children: _jsxs(CommandItem, { disabled: true, className: "text-muted-foreground", children: ["Type at least ", MIN_QUERY_LENGTH, " characters"] }) })), 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: "Clear assignee" })] }) })), canUseAi && (_jsx(CommandGroup, { heading: "Agent profiles", children: loadingProfiles ? (_jsxs(CommandItem, { disabled: true, children: [_jsx(Loader2, { className: "h-3.5 w-3.5 animate-spin" }), _jsx("span", { children: "Loading agent profiles..." })] })) : profilesError ? (_jsxs(CommandItem, { disabled: true, className: "text-destructive h-auto items-start gap-2 whitespace-normal opacity-100", children: [_jsx(X, { className: "mt-0.5 h-3.5 w-3.5 shrink-0" }), _jsx("span", { children: profilesError })] })) : filteredProfiles.length === 0 ? (_jsx(CommandItem, { disabled: true, className: "text-muted-foreground", children: "No agent profiles available." })) : (filteredProfiles.map((profile) => (_jsxs(CommandItem, { value: profile.id, onSelect: () => handleSelectProfile(profile), children: [_jsx(AgentProfileIcon, { svgIcon: profile.svgIcon, size: "xs", className: "bg-neutral-grey-5 text-neutral-grey-100 p-[3px]" }), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsx("div", { className: "truncate", children: profile.displayTitle || profile.name }), _jsx("div", { className: "text-muted-foreground truncate text-[10px]", children: profile.description || profile.id })] }), assigneeType === "Agent" &&
                                                value?.toLowerCase() === profile.id.toLowerCase() && (_jsx(Check, { className: "h-3.5 w-3.5" }))] }, profile.id)))) })), 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(User, { 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: "text-muted-foreground truncate text-[10px]", children: [user.userName, user.email ? ` • ${user.email}` : ""] })] }), assigneeType === "user" &&
                                                value?.toLowerCase() ===
                                                    user.userName.toLowerCase() && (_jsx(Check, { className: "h-3.5 w-3.5" }))] }, user.userName)))) })), canSearch &&
                                    !loading &&
                                    results.length === 0 &&
                                    filteredProfiles.length === 0 && (_jsx(CommandEmpty, { children: "No users found" }))] })] }) })] }));
}
//# sourceMappingURL=TaskAssigneePicker.js.map