'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useMemo, useState } from 'react';
import { Badge } from '../ui/badge.js';
import { Button } from '../ui/button.js';
import { Input } from '../ui/input.js';
import { Label } from '../ui/label.js';
import { Alert, AlertDescription } from '../ui/alert.js';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from '../ui/select.js';
import { AgentQuestionKind, AgentQuestionStatus, } from '../../../../../packages/core/src/domain/generated/output.js';
import { answerAgentQuestion, cancelAgentQuestion } from '../../app/actions/agent-questions.js';
const KIND_VARIANT = {
    [AgentQuestionKind.info]: 'secondary',
    [AgentQuestionKind.question]: 'default',
    [AgentQuestionKind.blocking]: 'destructive',
};
const STATUS_VARIANT = {
    [AgentQuestionStatus.pending]: 'default',
    [AgentQuestionStatus.answered]: 'secondary',
    [AgentQuestionStatus.cancelled]: 'outline',
    [AgentQuestionStatus.expired]: 'outline',
};
function parseOptions(json) {
    if (!json)
        return [];
    try {
        const parsed = JSON.parse(json);
        if (Array.isArray(parsed))
            return parsed.filter((v) => typeof v === 'string');
        return [];
    }
    catch {
        return [];
    }
}
export function AgentQuestionsInbox({ initialQuestions, initialStatusFilter = AgentQuestionStatus.pending, initialKindFilter = 'all', errorMessage = null, answerOverride, cancelOverride, currentActor = 'user:web', }) {
    const [statusFilter, setStatusFilter] = useState(initialStatusFilter);
    const [kindFilter, setKindFilter] = useState(initialKindFilter);
    const [pendingId, setPendingId] = useState(null);
    const [draftAnswers, setDraftAnswers] = useState({});
    const [error, setError] = useState(errorMessage);
    const [questions, setQuestions] = useState(initialQuestions);
    const filtered = useMemo(() => {
        return questions.filter((q) => {
            if (statusFilter !== 'all' && q.status !== statusFilter)
                return false;
            if (kindFilter !== 'all' && q.kind !== kindFilter)
                return false;
            return true;
        });
    }, [questions, statusFilter, kindFilter]);
    const submitAnswer = async (q, answer) => {
        if (!answer.trim()) {
            setError('Answer cannot be empty');
            return;
        }
        setError(null);
        setPendingId(q.id);
        try {
            const handler = answerOverride ?? answerAgentQuestion;
            const result = await handler({
                appId: q.appId ?? '',
                questionId: q.id,
                answer,
                answeredBy: currentActor,
            });
            if (!result.ok) {
                setError(result.error ?? 'Failed to submit answer');
                return;
            }
            setQuestions((prev) => prev.map((row) => row.id === q.id
                ? {
                    ...row,
                    status: AgentQuestionStatus.answered,
                    answer,
                    answeredBy: currentActor,
                    answeredAt: new Date(),
                }
                : row));
        }
        finally {
            setPendingId(null);
        }
    };
    const submitCancel = async (q) => {
        setError(null);
        setPendingId(q.id);
        try {
            const handler = cancelOverride ?? cancelAgentQuestion;
            const result = await handler({
                appId: q.appId ?? '',
                questionId: q.id,
                cancelledBy: currentActor,
            });
            if (!result.ok) {
                setError(result.error ?? 'Failed to cancel question');
                return;
            }
            setQuestions((prev) => prev.map((row) => row.id === q.id
                ? { ...row, status: AgentQuestionStatus.cancelled, answeredBy: currentActor }
                : row));
        }
        finally {
            setPendingId(null);
        }
    };
    return (_jsxs("section", { "data-testid": "agent-questions-inbox", className: "flex flex-col gap-4", "aria-label": "Agent questions inbox", children: [_jsxs("div", { className: "flex flex-wrap items-end gap-3", "data-testid": "inbox-filters", children: [_jsxs("div", { className: "flex flex-col gap-1", children: [_jsx(Label, { htmlFor: "status-filter", children: "Status" }), _jsxs(Select, { value: statusFilter, onValueChange: (v) => setStatusFilter(v), children: [_jsx(SelectTrigger, { id: "status-filter", className: "w-44", "data-testid": "status-filter", children: _jsx(SelectValue, {}) }), _jsxs(SelectContent, { children: [_jsx(SelectItem, { value: "all", children: "All" }), _jsx(SelectItem, { value: AgentQuestionStatus.pending, children: "Pending" }), _jsx(SelectItem, { value: AgentQuestionStatus.answered, children: "Answered" }), _jsx(SelectItem, { value: AgentQuestionStatus.cancelled, children: "Cancelled" }), _jsx(SelectItem, { value: AgentQuestionStatus.expired, children: "Expired" })] })] })] }), _jsxs("div", { className: "flex flex-col gap-1", children: [_jsx(Label, { htmlFor: "kind-filter", children: "Urgency" }), _jsxs(Select, { value: kindFilter, onValueChange: (v) => setKindFilter(v), children: [_jsx(SelectTrigger, { id: "kind-filter", className: "w-44", "data-testid": "kind-filter", children: _jsx(SelectValue, {}) }), _jsxs(SelectContent, { children: [_jsx(SelectItem, { value: "all", children: "All" }), _jsx(SelectItem, { value: AgentQuestionKind.info, children: "Info" }), _jsx(SelectItem, { value: AgentQuestionKind.question, children: "Question" }), _jsx(SelectItem, { value: AgentQuestionKind.blocking, children: "Blocking" })] })] })] })] }), error ? (_jsx(Alert, { variant: "destructive", "data-testid": "inbox-error", children: _jsx(AlertDescription, { children: error }) })) : null, filtered.length === 0 ? (_jsx("div", { "data-testid": "inbox-empty", className: "text-muted-foreground rounded border border-dashed p-6 text-center text-sm", children: "No agent questions match the current filters." })) : (_jsx("ul", { className: "flex flex-col gap-3", "data-testid": "inbox-list", children: filtered.map((q) => (_jsx(QuestionRow, { question: q, busy: pendingId === q.id, draftAnswer: draftAnswers[q.id] ?? '', onDraftChange: (value) => setDraftAnswers((prev) => ({ ...prev, [q.id]: value })), onSubmitAnswer: (answer) => submitAnswer(q, answer), onCancel: () => submitCancel(q) }, q.id))) }))] }));
}
function QuestionRow({ question, busy, draftAnswer, onDraftChange, onSubmitAnswer, onCancel, }) {
    const options = parseOptions(question.optionsJson);
    const isPending = question.status === AgentQuestionStatus.pending;
    return (_jsxs("li", { className: "flex flex-col gap-3 rounded border p-4", "data-testid": `question-row-${question.id}`, children: [_jsxs("header", { className: "flex flex-wrap items-center justify-between gap-2", children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx(Badge, { variant: KIND_VARIANT[question.kind] ?? 'secondary', className: "capitalize", children: question.kind }), _jsx(Badge, { variant: STATUS_VARIANT[question.status] ?? 'outline', className: "capitalize", children: question.status }), _jsxs("span", { className: "text-muted-foreground text-xs", children: ["run ", question.agentRunId.slice(0, 8)] })] }), question.featureId ? (_jsxs("span", { className: "text-muted-foreground text-xs", children: ["feature ", question.featureId.slice(0, 8)] })) : null] }), _jsx("p", { className: "text-sm whitespace-pre-wrap", "data-testid": `question-prompt-${question.id}`, children: question.prompt }), !isPending && question.answer ? (_jsxs("p", { className: "text-muted-foreground text-xs", "data-testid": `question-answer-${question.id}`, children: [question.status === AgentQuestionStatus.answered
                        ? 'Answered'
                        : question.status === AgentQuestionStatus.cancelled
                            ? 'Cancelled'
                            : 'Resolved', question.answeredBy ? ` by ${question.answeredBy}` : '', ": ", question.answer] })) : null, isPending ? (_jsxs("div", { className: "flex flex-col gap-2", children: [options.length > 0 ? (_jsx("div", { className: "flex flex-wrap gap-2", "data-testid": `question-options-${question.id}`, children: options.map((opt) => (_jsx(Button, { type: "button", variant: "default", size: "sm", disabled: busy, onClick: () => onSubmitAnswer(opt), "data-testid": `question-option-${question.id}-${opt}`, children: opt }, opt))) })) : (_jsxs("div", { className: "flex items-center gap-2", children: [_jsx(Input, { value: draftAnswer, onChange: (e) => onDraftChange(e.target.value), placeholder: "Type an answer\u2026", disabled: busy, "data-testid": `question-input-${question.id}` }), _jsx(Button, { type: "button", size: "sm", disabled: busy, onClick: () => onSubmitAnswer(draftAnswer), "data-testid": `question-submit-${question.id}`, children: "Submit" })] })), _jsx("div", { children: _jsx(Button, { type: "button", variant: "ghost", size: "sm", disabled: busy, onClick: onCancel, "data-testid": `question-cancel-${question.id}`, children: "Cancel question" }) })] })) : null] }));
}
