import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useEffect, useMemo, useState } from "react";
import { toast } from "sonner";
import { Bot, Loader2, UserPlus } from "lucide-react";
import { Button } from "../../components/ui/button";
import { Dialog, DialogContent, DialogFooter } from "../../components/ui/dialog";
import { StyledDialogTitle } from "../../components/ui/styled-dialog-title";
import { Label } from "../../components/ui/label";
import { Select } from "../../components/ui/select";
import { Textarea } from "../../components/ui/textarea";
import { getAiProfilesErrorMessage, loadAiProfiles, } from "../../editor/services/aiService";
import { updateTask } from "../services/taskService";
import { DEFAULT_INITIAL_PROMPT, getStoredPrompt, mergeAgentConfigIntoResultData, } from "../taskAgentConfig";
import { LicenseFeatures, useFeature } from "../../licensing";
export function AssignAgentDialog(props) {
    const { open, task, onOpenChange, onAssigned } = props;
    const canUseAi = useFeature(LicenseFeatures.AI);
    const [profiles, setProfiles] = useState([]);
    const [loadingProfiles, setLoadingProfiles] = useState(false);
    const [profilesError, setProfilesError] = useState(null);
    const [selectedProfileId, setSelectedProfileId] = useState("");
    const [initialPrompt, setInitialPrompt] = useState(DEFAULT_INITIAL_PROMPT);
    const [submitting, setSubmitting] = useState(false);
    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) {
                setProfiles([]);
                const message = getAiProfilesErrorMessage(error);
                setProfilesError(message);
                toast.error(message);
            }
        })
            .finally(() => {
            if (!cancelled)
                setLoadingProfiles(false);
        });
        return () => {
            cancelled = true;
        };
    }, [canUseAi, open]);
    useEffect(() => {
        if (!open || !task)
            return;
        const existingPrompt = getStoredPrompt(task.resultData);
        setInitialPrompt(existingPrompt || DEFAULT_INITIAL_PROMPT);
        setSelectedProfileId(task.assigneeType === "Agent" ? task.assigneeId || "" : "");
    }, [open, task]);
    const profileOptions = useMemo(() => profiles.map((profile) => ({
        value: profile.id,
        label: profile.displayTitle || profile.name,
        description: profile.description || undefined,
    })), [profiles]);
    const submit = async () => {
        if (!canUseAi) {
            toast.error("AI features are unavailable with the current license.");
            return;
        }
        if (!task)
            return;
        if (!selectedProfileId) {
            toast.error("Please select an agent profile");
            return;
        }
        const promptText = initialPrompt.trim() || DEFAULT_INITIAL_PROMPT;
        setSubmitting(true);
        try {
            const result = await updateTask({
                taskId: task.taskId,
                assigneeType: "Agent",
                assigneeId: selectedProfileId,
                resultData: mergeAgentConfigIntoResultData(task.resultData, promptText, selectedProfileId),
            });
            if (result.type !== "success") {
                toast.error(result.summary || "Failed to assign agent");
                return;
            }
            toast.success("Agent assigned");
            onOpenChange(false);
            await onAssigned();
        }
        finally {
            setSubmitting(false);
        }
    };
    return (_jsx(Dialog, { open: open, onOpenChange: onOpenChange, children: _jsxs(DialogContent, { className: "max-w-lg", children: [_jsx(StyledDialogTitle, { icon: _jsx(UserPlus, { strokeWidth: 1 }), title: "Assign Agent", subtitle: task ? `Assign an agent to ${task.taskKey || task.taskId.slice(0, 8).toUpperCase()}` : "Assign an agent to this task" }), _jsxs("div", { className: "grid gap-5 p-6", children: [_jsxs("div", { className: "grid gap-2", children: [_jsx(Label, { htmlFor: "task-agent-profile", children: "Agent profile" }), _jsx(Select, { id: "task-agent-profile", value: selectedProfileId, onValueChange: setSelectedProfileId, options: profileOptions, placeholder: loadingProfiles ? "Loading profiles..." : "Select an agent profile", searchable: true, disabled: loadingProfiles || submitting }), profilesError && (_jsx("div", { className: "text-xs text-destructive", children: profilesError })), !loadingProfiles && !profilesError && profileOptions.length === 0 && (_jsx("div", { className: "text-xs text-muted-foreground", children: "No agent profiles available." }))] }), _jsxs("div", { className: "grid gap-2", children: [_jsx(Label, { htmlFor: "task-agent-prompt", children: "Initial prompt" }), _jsx(Textarea, { id: "task-agent-prompt", value: initialPrompt, onChange: (event) => setInitialPrompt(event.target.value), rows: 4, disabled: submitting, placeholder: DEFAULT_INITIAL_PROMPT }), _jsxs("div", { className: "flex items-center gap-1.5 text-xs text-muted-foreground", children: [_jsx(Bot, { className: "h-3.5 w-3.5" }), "The agent receives this before starting task execution."] })] })] }), _jsxs(DialogFooter, { className: "p-4", children: [_jsx(Button, { variant: "outline", onClick: () => onOpenChange(false), disabled: submitting, children: "Cancel" }), _jsx(Button, { onClick: submit, disabled: submitting || loadingProfiles || !selectedProfileId, children: submitting ? (_jsxs(_Fragment, { children: [_jsx(Loader2, { className: "mr-2 h-4 w-4 animate-spin" }), "Assigning..."] })) : ("Assign Agent") })] })] }) }));
}
//# sourceMappingURL=AssignAgentDialog.js.map