import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useMemo, useState } from "react";
import { toast } from "sonner";
import { CheckCircle2, Loader2, MessageCircleWarning, XCircle, } 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 { Textarea } from "../../components/ui/textarea";
import { MentionTextarea } from "../../components/ui/mention-textarea";
import { useEditContext } from "../../editor/client/editContext";
import { getAgent, startAgent } from "../../editor/services/agentService";
import { addComment, updateTask } from "../services/taskService";
function buildReviewRejectionMessage(reason) {
    return [
        "The task was rejected during review and has been moved back to open.",
        "Please address the following feedback before resubmitting it for review:",
        "",
        reason,
    ].join("\n");
}
export function TaskReviewActions(props) {
    const { task, agentId = null, canEdit, onTaskChanged, onTaskApproved, approveLast = false, className, } = props;
    const editContext = useEditContext();
    const [rejectDialogOpen, setRejectDialogOpen] = useState(false);
    const [rejectReason, setRejectReason] = useState("");
    const [submittingAction, setSubmittingAction] = useState(null);
    const isReviewTask = task?.status === "Review";
    const canSendToAgent = useMemo(() => Boolean(agentId && editContext?.sessionId), [agentId, editContext?.sessionId]);
    if (!task || !canEdit || !isReviewTask) {
        return null;
    }
    const handleApprove = async () => {
        setSubmittingAction("approve");
        try {
            const result = await updateTask({
                taskId: task.taskId,
                status: "Done",
            });
            if (result.type !== "success") {
                toast.error(result.summary || "Failed to approve task");
                return;
            }
            await (onTaskApproved ?? onTaskChanged)?.();
        }
        finally {
            setSubmittingAction(null);
        }
    };
    const handleReject = async () => {
        const trimmedReason = rejectReason.trim();
        if (!trimmedReason) {
            toast.error("A rejection reason is required");
            return;
        }
        setSubmittingAction("reject");
        try {
            let feedbackSentToAgent = false;
            if (agentId && editContext?.sessionId) {
                try {
                    const agentDetails = await getAgent(agentId);
                    if (agentDetails.profileId) {
                        await startAgent({
                            agentId,
                            message: buildReviewRejectionMessage(trimmedReason),
                            sessionId: editContext.sessionId,
                            profileId: agentDetails.profileId,
                            model: agentDetails.model,
                        });
                        feedbackSentToAgent = true;
                    }
                }
                catch (error) {
                    console.warn("[TaskReviewActions] Failed to send review feedback to agent", error);
                }
            }
            if (!feedbackSentToAgent) {
                const commentResult = await addComment({
                    taskId: task.taskId,
                    text: `Review rejected: ${trimmedReason}`,
                });
                if (commentResult.type !== "success") {
                    toast.error(commentResult.summary || "Failed to add rejection comment");
                    return;
                }
            }
            const updateResult = await updateTask({
                taskId: task.taskId,
                status: "InProgress",
            });
            if (updateResult.type !== "success") {
                toast.error(updateResult.summary || "Failed to reopen task");
                return;
            }
            setRejectReason("");
            setRejectDialogOpen(false);
            toast.success(feedbackSentToAgent
                ? "Feedback sent to the agent and task reopened"
                : "Rejection reason added and task reopened");
            await onTaskChanged?.();
        }
        finally {
            setSubmittingAction(null);
        }
    };
    const approveButton = (_jsxs(Button, { type: "button", size: "sm", onClick: () => void handleApprove(), disabled: submittingAction !== null, children: [submittingAction === "approve" ? (_jsx(Loader2, { strokeWidth: 1, className: "mr-2 h-4 w-4 animate-spin" })) : (_jsx(CheckCircle2, { strokeWidth: 1, className: "mr-2 h-4 w-4" })), "Approve"] }));
    const rejectButton = (_jsxs(Button, { type: "button", size: "sm", variant: "outline", onClick: () => setRejectDialogOpen(true), disabled: submittingAction !== null, children: [_jsx(XCircle, { strokeWidth: 1, className: "mr-2 h-4 w-4" }), "Reject"] }));
    return (_jsxs(_Fragment, { children: [_jsx("div", { className: className ?? "flex flex-wrap items-center gap-2", children: approveLast ? (_jsxs(_Fragment, { children: [rejectButton, approveButton] })) : (_jsxs(_Fragment, { children: [approveButton, rejectButton] })) }), _jsx(Dialog, { open: rejectDialogOpen, onOpenChange: setRejectDialogOpen, children: _jsxs(DialogContent, { className: "sm:max-w-lg", children: [_jsx(StyledDialogTitle, { icon: _jsx(MessageCircleWarning, { strokeWidth: 1 }), title: "Reject task review", subtitle: canSendToAgent
                                ? "Send feedback to the linked agent and move the task back to open."
                                : "Save feedback as a task comment and move the task back to open." }), _jsxs("div", { className: "grid gap-2 p-6", children: [_jsx(Label, { htmlFor: "task-review-reject-reason", children: "Reason" }), canSendToAgent ? (_jsx(Textarea, { id: "task-review-reject-reason", value: rejectReason, onChange: (event) => setRejectReason(event.target.value), rows: 6, placeholder: "Explain what needs to change before this task can be approved...", disabled: submittingAction === "reject" })) : (_jsx(MentionTextarea, { id: "task-review-reject-reason", value: rejectReason, onValueChange: setRejectReason, rows: 6, placeholder: "Explain what needs to change before this task can be approved...", disabled: submittingAction === "reject" })), _jsxs("div", { className: "text-neutral-grey-50 flex items-center gap-2 text-xs", children: [_jsx(MessageCircleWarning, { strokeWidth: 1, className: "h-4 w-4 shrink-0" }), _jsx("span", { children: canSendToAgent
                                                ? "The linked agent will receive this feedback."
                                                : "No linked agent is available, so the feedback will be stored as a comment." })] })] }), _jsxs(DialogFooter, { className: "p-4", children: [_jsx(Button, { type: "button", variant: "outline", onClick: () => setRejectDialogOpen(false), disabled: submittingAction === "reject", children: "Cancel" }), _jsxs(Button, { type: "button", variant: "destructive", onClick: () => void handleReject(), disabled: submittingAction === "reject", children: [submittingAction === "reject" ? (_jsx(Loader2, { strokeWidth: 1, className: "mr-2 h-4 w-4 animate-spin" })) : null, "Reject and reopen"] })] })] }) })] }));
}
//# sourceMappingURL=TaskReviewActions.js.map