'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState } from 'react';
import { Button } from '../ui/button.js';
import { Label } from '../ui/label.js';
import { Input } from '../ui/input.js';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from '../ui/select.js';
import { Switch } from '../ui/switch.js';
import { Alert, AlertDescription } from '../ui/alert.js';
import { SupervisorAutonomy } from '../../../../../packages/core/src/domain/generated/output.js';
import { configureSupervisor } from '../../app/actions/configure-supervisor.js';
const AUTONOMY_OPTIONS = [
    {
        value: SupervisorAutonomy.advisory,
        label: 'Advisory',
        description: 'Supervisor recommends, user always decides. Safest default.',
    },
    {
        value: SupervisorAutonomy.cosign,
        label: 'Co-sign',
        description: 'Both supervisor and user must approve before a gate can pass.',
    },
    {
        value: SupervisorAutonomy.autonomous,
        label: 'Autonomous',
        description: 'Supervisor acts on the user’s behalf within configured policy.',
    },
];
const GATE_KEYS = ['prd', 'plan', 'merge'];
function parseGateAuthority(json) {
    if (!json)
        return {};
    try {
        const parsed = JSON.parse(json);
        if (!parsed || typeof parsed !== 'object')
            return {};
        return parsed;
    }
    catch {
        return {};
    }
}
export function SupervisorConfigForm({ scopeType, scopeId, featureId, initialPolicy, onSubmitOverride, forceState = 'default', }) {
    const initialAutonomy = initialPolicy?.autonomyLevel ?? SupervisorAutonomy.advisory;
    const initialGate = parseGateAuthority(initialPolicy?.gateAuthorityJson);
    const [autonomyLevel, setAutonomyLevel] = useState(initialAutonomy);
    const [modelId, setModelId] = useState(initialPolicy?.modelId ?? '');
    const [promptVersion, setPromptVersion] = useState(initialPolicy?.promptVersion ?? '');
    const [gateAuthority, setGateAuthority] = useState(initialGate);
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [error, setError] = useState(forceState === 'error' ? 'Failed to save supervisor policy' : null);
    const [savedAt, setSavedAt] = useState(null);
    const loading = forceState === 'loading' || isSubmitting;
    const handleSubmit = async (e) => {
        e.preventDefault();
        setError(null);
        setIsSubmitting(true);
        const input = {
            scopeType,
            scopeId,
            featureId,
            autonomyLevel,
            modelId: modelId.trim() || undefined,
            promptVersion: promptVersion.trim() || undefined,
            gateAuthority: Object.keys(gateAuthority).length > 0 ? gateAuthority : undefined,
        };
        try {
            const result = onSubmitOverride
                ? await onSubmitOverride(input)
                : await configureSupervisor(input);
            if (!result.ok) {
                setError(result.error ?? 'Failed to save supervisor policy');
            }
            else {
                setSavedAt(new Date());
            }
        }
        catch (err) {
            setError(err instanceof Error ? err.message : 'Failed to save supervisor policy');
        }
        finally {
            setIsSubmitting(false);
        }
    };
    const setGate = (gate, value) => {
        setGateAuthority((prev) => {
            const next = { ...prev };
            if (value === 'inherit') {
                delete next[gate];
            }
            else {
                next[gate] = value;
            }
            return next;
        });
    };
    return (_jsxs("form", { onSubmit: handleSubmit, "data-testid": "supervisor-config-form", className: "flex flex-col gap-6 rounded-lg border p-6", "aria-busy": loading, children: [_jsxs("header", { className: "flex flex-col gap-1", children: [_jsx("h2", { className: "text-lg font-semibold", children: "Supervisor agent" }), _jsx("p", { className: "text-muted-foreground text-sm", children: featureId
                            ? 'Per-feature override. Falls back to the scope-level policy when unset.'
                            : `${scopeType.charAt(0).toUpperCase() + scopeType.slice(1)}-level policy. Applies to every feature unless overridden.` })] }), _jsxs("div", { className: "flex flex-col gap-2", children: [_jsx(Label, { htmlFor: "autonomyLevel", children: "Autonomy level" }), _jsxs(Select, { value: autonomyLevel, onValueChange: (v) => setAutonomyLevel(v), disabled: loading, children: [_jsx(SelectTrigger, { id: "autonomyLevel", "data-testid": "autonomy-trigger", children: _jsx(SelectValue, {}) }), _jsx(SelectContent, { children: AUTONOMY_OPTIONS.map((opt) => (_jsx(SelectItem, { value: opt.value, children: opt.label }, opt.value))) })] }), _jsx("p", { className: "text-muted-foreground text-xs", children: AUTONOMY_OPTIONS.find((o) => o.value === autonomyLevel)?.description })] }), _jsxs("div", { className: "flex flex-col gap-2", children: [_jsx(Label, { htmlFor: "modelId", children: "Evaluator model" }), _jsx(Input, { id: "modelId", "data-testid": "model-id-input", placeholder: "e.g. claude-sonnet-4", value: modelId, onChange: (e) => setModelId(e.target.value), disabled: loading })] }), _jsxs("div", { className: "flex flex-col gap-2", children: [_jsx(Label, { htmlFor: "promptVersion", children: "Prompt version" }), _jsx(Input, { id: "promptVersion", "data-testid": "prompt-version-input", placeholder: "e.g. v1", value: promptVersion, onChange: (e) => setPromptVersion(e.target.value), disabled: loading })] }), _jsxs("fieldset", { className: "flex flex-col gap-3", disabled: loading, children: [_jsx("legend", { className: "text-sm font-medium", children: "Per-gate authority" }), GATE_KEYS.map((gate) => {
                        const current = gateAuthority[gate] ?? 'inherit';
                        const checkboxId = `gate-${gate}`;
                        return (_jsxs("div", { className: "flex items-center justify-between gap-3", "data-testid": `gate-row-${gate}`, children: [_jsx(Label, { htmlFor: checkboxId, className: "capitalize", children: gate }), _jsxs(Select, { value: current, onValueChange: (v) => setGate(gate, v), children: [_jsx(SelectTrigger, { id: checkboxId, className: "w-44", "data-testid": `gate-trigger-${gate}`, children: _jsx(SelectValue, {}) }), _jsxs(SelectContent, { children: [_jsx(SelectItem, { value: "inherit", children: "Inherit" }), AUTONOMY_OPTIONS.map((opt) => (_jsx(SelectItem, { value: opt.value, children: opt.label }, opt.value)))] })] })] }, gate));
                    })] }), initialPolicy ? (_jsxs("div", { className: "flex items-center justify-between rounded border px-3 py-2", children: [_jsxs("div", { className: "flex flex-col", children: [_jsxs("span", { className: "text-sm font-medium", children: ["Currently ", initialPolicy.enabled ? 'enabled' : 'disabled'] }), _jsx("span", { className: "text-muted-foreground text-xs", children: "Toggle without changing other settings" })] }), _jsx(Switch, { checked: initialPolicy.enabled, disabled: true, "data-testid": "enabled-readonly", "aria-label": "Supervisor enabled (read-only \u2014 toggle via the Enable/Disable buttons)" })] })) : null, error ? (_jsx(Alert, { variant: "destructive", "data-testid": "form-error", children: _jsx(AlertDescription, { children: error }) })) : null, savedAt ? (_jsx(Alert, { "data-testid": "form-saved", children: _jsxs(AlertDescription, { children: ["Saved at ", savedAt.toLocaleTimeString()] }) })) : null, _jsx("div", { className: "flex justify-end", children: _jsx(Button, { type: "submit", disabled: loading, "data-testid": "submit", children: loading ? 'Saving…' : initialPolicy ? 'Update supervisor' : 'Save supervisor' }) })] }));
}
