'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState, useTransition, useRef, useEffect } from 'react';
import { GitBranch, Check } from 'lucide-react';
import { toast } from 'sonner';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '../../ui/card.js';
import { Label } from '../../ui/label.js';
import { Input } from '../../ui/input.js';
import { Switch } from '../../ui/switch.js';
import { Separator } from '../../ui/separator.js';
import { updateSettingsAction } from '../../../app/actions/update-settings.js';
import { TimeoutSlider } from '../../features/settings/timeout-slider.js';
export function WorkflowSettingsSection({ workflow }) {
    const [openPr, setOpenPr] = useState(workflow.openPrOnImplementationComplete);
    const [pushOnComplete, setPushOnComplete] = useState(workflow.approvalGateDefaults.pushOnImplementationComplete);
    const [allowPrd, setAllowPrd] = useState(workflow.approvalGateDefaults.allowPrd);
    const [allowPlan, setAllowPlan] = useState(workflow.approvalGateDefaults.allowPlan);
    const [allowMerge, setAllowMerge] = useState(workflow.approvalGateDefaults.allowMerge);
    const [ciWatchEnabled, setCiWatchEnabled] = useState(workflow.ciWatchEnabled !== false);
    const [ciMaxFix, setCiMaxFix] = useState(workflow.ciMaxFixAttempts != null ? String(workflow.ciMaxFixAttempts) : '');
    const [ciTimeout, setCiTimeout] = useState(workflow.ciWatchTimeoutMs != null ? String(Math.round(workflow.ciWatchTimeoutMs / 1000)) : '');
    const [ciLogMax, setCiLogMax] = useState(workflow.ciLogMaxChars != null ? String(workflow.ciLogMaxChars) : '');
    const [ciPollInterval, setCiPollInterval] = useState(workflow.ciWatchPollIntervalSeconds != null ? String(workflow.ciWatchPollIntervalSeconds) : '');
    const [hideCiStatus, setHideCiStatus] = useState(workflow.hideCiStatus !== false);
    // Per-stage timeout states (seconds for display)
    // Defaults: feature agent stages = 1_800_000 ms (1800s), analyze-repo = 600_000 ms (600s)
    const st = workflow.stageTimeouts;
    const [analyzeTimeout, setAnalyzeTimeout] = useState(String(Math.round((st?.analyzeMs ?? 1_800_000) / 1000)));
    const [requirementsTimeout, setRequirementsTimeout] = useState(String(Math.round((st?.requirementsMs ?? 1_800_000) / 1000)));
    const [researchTimeout, setResearchTimeout] = useState(String(Math.round((st?.researchMs ?? 1_800_000) / 1000)));
    const [planTimeout, setPlanTimeout] = useState(String(Math.round((st?.planMs ?? 1_800_000) / 1000)));
    const [implementTimeout, setImplementTimeout] = useState(String(Math.round((st?.implementMs ?? 1_800_000) / 1000)));
    const [fastImplementTimeout, setFastImplementTimeout] = useState(String(Math.round((st?.fastImplementMs ?? 1_800_000) / 1000)));
    const [mergeTimeout, setMergeTimeout] = useState(String(Math.round((st?.mergeMs ?? 1_800_000) / 1000)));
    // Analyze-repo agent timeout state
    const art = workflow.analyzeRepoTimeouts;
    const [analyzeRepoTimeout, setAnalyzeRepoTimeout] = useState(String(Math.round((art?.analyzeMs ?? 600_000) / 1000)));
    const [isPending, startTransition] = useTransition();
    const [showSaved, setShowSaved] = useState(false);
    const prevPendingRef = useRef(false);
    useEffect(() => {
        if (prevPendingRef.current && !isPending) {
            setShowSaved(true);
            const timer = setTimeout(() => setShowSaved(false), 2000);
            return () => clearTimeout(timer);
        }
        prevPendingRef.current = isPending;
    }, [isPending]);
    function parseOptionalInt(value) {
        if (value === '')
            return undefined;
        const n = parseInt(value, 10);
        return Number.isNaN(n) || n <= 0 ? undefined : n;
    }
    function secondsToMs(val) {
        const n = parseOptionalInt(val);
        return n != null ? n * 1000 : undefined;
    }
    function buildPayload(overrides = {}) {
        const timeoutSeconds = parseOptionalInt(overrides.ciTimeout ?? ciTimeout);
        return {
            workflow: {
                openPrOnImplementationComplete: overrides.openPr ?? openPr,
                approvalGateDefaults: {
                    pushOnImplementationComplete: overrides.pushOnComplete ?? pushOnComplete,
                    allowPrd: overrides.allowPrd ?? allowPrd,
                    allowPlan: overrides.allowPlan ?? allowPlan,
                    allowMerge: overrides.allowMerge ?? allowMerge,
                },
                ciWatchEnabled: overrides.ciWatchEnabled ?? ciWatchEnabled,
                hideCiStatus: overrides.hideCiStatus ?? hideCiStatus,
                ciMaxFixAttempts: parseOptionalInt(overrides.ciMaxFix ?? ciMaxFix),
                ciWatchTimeoutMs: timeoutSeconds != null ? timeoutSeconds * 1000 : undefined,
                ciLogMaxChars: parseOptionalInt(overrides.ciLogMax ?? ciLogMax),
                ciWatchPollIntervalSeconds: parseOptionalInt(overrides.ciPollInterval ?? ciPollInterval),
                stageTimeouts: {
                    analyzeMs: secondsToMs(overrides.analyzeTimeout ?? analyzeTimeout),
                    requirementsMs: secondsToMs(overrides.requirementsTimeout ?? requirementsTimeout),
                    researchMs: secondsToMs(overrides.researchTimeout ?? researchTimeout),
                    planMs: secondsToMs(overrides.planTimeout ?? planTimeout),
                    implementMs: secondsToMs(overrides.implementTimeout ?? implementTimeout),
                    fastImplementMs: secondsToMs(overrides.fastImplementTimeout ?? fastImplementTimeout),
                    mergeMs: secondsToMs(overrides.mergeTimeout ?? mergeTimeout),
                },
                analyzeRepoTimeouts: {
                    analyzeMs: secondsToMs(overrides.analyzeRepoTimeout ?? analyzeRepoTimeout),
                },
            },
        };
    }
    function save(overrides = {}) {
        startTransition(async () => {
            const result = await updateSettingsAction(buildPayload(overrides));
            if (!result.success) {
                toast.error(result.error ?? 'Failed to save workflow settings');
            }
        });
    }
    function handleSwitchChange(key, setter, value) {
        setter(value);
        save({ [key]: value });
    }
    function handleFieldBlur(key, currentValue, originalValue) {
        if (currentValue !== originalValue) {
            save({ [key]: currentValue });
        }
    }
    const originalCiMaxFix = workflow.ciMaxFixAttempts != null ? String(workflow.ciMaxFixAttempts) : '';
    const originalCiTimeout = workflow.ciWatchTimeoutMs != null ? String(Math.round(workflow.ciWatchTimeoutMs / 1000)) : '';
    const originalCiLogMax = workflow.ciLogMaxChars != null ? String(workflow.ciLogMaxChars) : '';
    const originalCiPollInterval = workflow.ciWatchPollIntervalSeconds != null ? String(workflow.ciWatchPollIntervalSeconds) : '';
    const originalAnalyzeTimeout = st?.analyzeMs != null ? String(Math.round(st.analyzeMs / 1000)) : '';
    const originalRequirementsTimeout = st?.requirementsMs != null ? String(Math.round(st.requirementsMs / 1000)) : '';
    const originalResearchTimeout = st?.researchMs != null ? String(Math.round(st.researchMs / 1000)) : '';
    const originalPlanTimeout = st?.planMs != null ? String(Math.round(st.planMs / 1000)) : '';
    const originalImplementTimeout = st?.implementMs != null ? String(Math.round(st.implementMs / 1000)) : '';
    const originalFastImplementTimeout = st?.fastImplementMs != null ? String(Math.round(st.fastImplementMs / 1000)) : '';
    const originalMergeTimeout = st?.mergeMs != null ? String(Math.round(st.mergeMs / 1000)) : '';
    const originalAnalyzeRepoTimeout = art?.analyzeMs != null ? String(Math.round(art.analyzeMs / 1000)) : '';
    const FEATURE_AGENT_FIELDS = [
        {
            key: 'analyzeTimeout',
            label: 'Analyze',
            defaultSeconds: 1800,
            state: analyzeTimeout,
            setter: setAnalyzeTimeout,
            original: originalAnalyzeTimeout,
        },
        {
            key: 'requirementsTimeout',
            label: 'Requirements',
            defaultSeconds: 1800,
            state: requirementsTimeout,
            setter: setRequirementsTimeout,
            original: originalRequirementsTimeout,
        },
        {
            key: 'researchTimeout',
            label: 'Research',
            defaultSeconds: 1800,
            state: researchTimeout,
            setter: setResearchTimeout,
            original: originalResearchTimeout,
        },
        {
            key: 'planTimeout',
            label: 'Plan',
            defaultSeconds: 1800,
            state: planTimeout,
            setter: setPlanTimeout,
            original: originalPlanTimeout,
        },
        {
            key: 'implementTimeout',
            label: 'Implement',
            defaultSeconds: 1800,
            state: implementTimeout,
            setter: setImplementTimeout,
            original: originalImplementTimeout,
        },
        {
            key: 'fastImplementTimeout',
            label: 'Fast Implement',
            defaultSeconds: 1800,
            state: fastImplementTimeout,
            setter: setFastImplementTimeout,
            original: originalFastImplementTimeout,
        },
        {
            key: 'mergeTimeout',
            label: 'Merge',
            defaultSeconds: 1800,
            state: mergeTimeout,
            setter: setMergeTimeout,
            original: originalMergeTimeout,
        },
    ];
    const ANALYZE_REPO_FIELDS = [
        {
            key: 'analyzeRepoTimeout',
            label: 'Analyze',
            defaultSeconds: 600,
            state: analyzeRepoTimeout,
            setter: setAnalyzeRepoTimeout,
            original: originalAnalyzeRepoTimeout,
        },
    ];
    return (_jsxs(Card, { id: "workflow", className: "scroll-mt-6", "data-testid": "workflow-settings-section", children: [_jsxs(CardHeader, { children: [_jsxs("div", { className: "flex items-center justify-between", children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx(GitBranch, { className: "text-muted-foreground h-4 w-4" }), _jsx(CardTitle, { children: "Workflow" })] }), isPending ? _jsx("span", { className: "text-muted-foreground text-xs", children: "Saving..." }) : null, showSaved && !isPending ? (_jsxs("span", { className: "flex items-center gap-1 text-xs text-green-600", children: [_jsx(Check, { className: "h-3 w-3" }), "Saved"] })) : null] }), _jsx(CardDescription, { children: "Configure PR behavior, approval gates, and CI settings" })] }), _jsxs(CardContent, { className: "space-y-4", children: [_jsxs("div", { className: "space-y-3", children: [_jsxs("div", { className: "flex items-center justify-between gap-4", children: [_jsxs("div", { className: "space-y-0.5", children: [_jsx(Label, { htmlFor: "open-pr", children: "Open PR on implementation complete" }), _jsx("p", { className: "text-muted-foreground text-xs", children: "Automatically create a pull request when the agent finishes" })] }), _jsx(Switch, { id: "open-pr", "data-testid": "switch-open-pr", checked: openPr, onCheckedChange: (v) => handleSwitchChange('openPr', setOpenPr, v) })] }), _jsxs("div", { className: "flex items-center justify-between gap-4", children: [_jsxs("div", { className: "space-y-0.5", children: [_jsx(Label, { htmlFor: "push-on-complete", children: "Push on implementation complete" }), _jsx("p", { className: "text-muted-foreground text-xs", children: "Push the branch to remote when implementation is done" })] }), _jsx(Switch, { id: "push-on-complete", "data-testid": "switch-push-on-complete", checked: pushOnComplete, onCheckedChange: (v) => handleSwitchChange('pushOnComplete', setPushOnComplete, v) })] })] }), _jsx(Separator, {}), _jsxs("div", { className: "space-y-3", children: [_jsx("h3", { className: "text-sm font-semibold", children: "Approval Gates" }), _jsxs("div", { className: "flex items-center justify-between gap-4", children: [_jsxs("div", { className: "space-y-0.5", children: [_jsx(Label, { htmlFor: "allow-prd", children: "PRD auto-approval" }), _jsx("p", { className: "text-muted-foreground text-xs", children: "Skip manual approval for product requirement documents" })] }), _jsx(Switch, { id: "allow-prd", "data-testid": "switch-allow-prd", checked: allowPrd, onCheckedChange: (v) => handleSwitchChange('allowPrd', setAllowPrd, v) })] }), _jsxs("div", { className: "flex items-center justify-between gap-4", children: [_jsxs("div", { className: "space-y-0.5", children: [_jsx(Label, { htmlFor: "allow-plan", children: "Plan auto-approval" }), _jsx("p", { className: "text-muted-foreground text-xs", children: "Skip manual approval for implementation plans" })] }), _jsx(Switch, { id: "allow-plan", "data-testid": "switch-allow-plan", checked: allowPlan, onCheckedChange: (v) => handleSwitchChange('allowPlan', setAllowPlan, v) })] }), _jsxs("div", { className: "flex items-center justify-between gap-4", children: [_jsxs("div", { className: "space-y-0.5", children: [_jsx(Label, { htmlFor: "allow-merge", children: "Merge auto-approval" }), _jsx("p", { className: "text-muted-foreground text-xs", children: "Skip manual approval for PR merges" })] }), _jsx(Switch, { id: "allow-merge", "data-testid": "switch-allow-merge", checked: allowMerge, onCheckedChange: (v) => handleSwitchChange('allowMerge', setAllowMerge, v) })] })] }), _jsx(Separator, {}), _jsxs("div", { className: "space-y-3", children: [_jsx("h3", { className: "text-sm font-semibold", children: "CI Settings" }), _jsxs("div", { className: "flex items-center justify-between gap-4", children: [_jsxs("div", { className: "space-y-0.5", children: [_jsx(Label, { htmlFor: "ci-watch-enabled", children: "CI watch/fix loop" }), _jsx("p", { className: "text-muted-foreground text-xs", children: "Watch CI status after push and auto-fix failures. Disable to avoid GitHub API rate limits." })] }), _jsx(Switch, { id: "ci-watch-enabled", "data-testid": "switch-ci-watch-enabled", checked: ciWatchEnabled, onCheckedChange: (v) => handleSwitchChange('ciWatchEnabled', setCiWatchEnabled, v) })] }), _jsxs("div", { className: "space-y-1.5", children: [_jsx(Label, { htmlFor: "ci-max-fix", children: "Max fix attempts" }), _jsx(Input, { id: "ci-max-fix", "data-testid": "ci-max-fix-input", type: "text", inputMode: "numeric", pattern: "[0-9]*", min: 1, max: 10, placeholder: "e.g., 3", value: ciMaxFix, onChange: (e) => setCiMaxFix(e.target.value), onBlur: () => handleFieldBlur('ciMaxFix', ciMaxFix, originalCiMaxFix) }), _jsx("p", { className: "text-muted-foreground text-xs", children: "How many times the agent retries fixing CI failures" })] }), _jsxs("div", { className: "space-y-1.5", children: [_jsx(Label, { htmlFor: "ci-timeout", children: "Watch timeout (seconds)" }), _jsx(Input, { id: "ci-timeout", "data-testid": "ci-timeout-input", type: "text", inputMode: "numeric", pattern: "[0-9]*", placeholder: "e.g., 300", value: ciTimeout, onChange: (e) => setCiTimeout(e.target.value), onBlur: () => handleFieldBlur('ciTimeout', ciTimeout, originalCiTimeout) }), _jsx("p", { className: "text-muted-foreground text-xs", children: "How long to wait for CI to complete before timing out" })] }), _jsxs("div", { className: "space-y-1.5", children: [_jsx(Label, { htmlFor: "ci-log-max", children: "Max log characters" }), _jsx(Input, { id: "ci-log-max", "data-testid": "ci-log-max-input", type: "text", inputMode: "numeric", pattern: "[0-9]*", placeholder: "e.g., 50000", value: ciLogMax, onChange: (e) => setCiLogMax(e.target.value), onBlur: () => handleFieldBlur('ciLogMax', ciLogMax, originalCiLogMax) }), _jsx("p", { className: "text-muted-foreground text-xs", children: "Maximum characters to capture from CI logs" })] }), _jsxs("div", { className: "space-y-1.5", children: [_jsx(Label, { htmlFor: "ci-poll-interval", children: "Poll interval (seconds)" }), _jsx(Input, { id: "ci-poll-interval", "data-testid": "ci-poll-interval-input", type: "text", inputMode: "numeric", pattern: "[0-9]*", placeholder: "e.g., 30", value: ciPollInterval, onChange: (e) => setCiPollInterval(e.target.value), onBlur: () => handleFieldBlur('ciPollInterval', ciPollInterval, originalCiPollInterval) }), _jsx("p", { className: "text-muted-foreground text-xs", children: "How often to poll GitHub for CI run status updates" })] }), _jsxs("div", { className: "flex items-center justify-between gap-4", children: [_jsxs("div", { className: "space-y-0.5", children: [_jsx(Label, { htmlFor: "hide-ci-status", children: "Hide CI Status" }), _jsx("p", { className: "text-muted-foreground text-xs", children: "Hide CI status badges from feature drawer and merge review" })] }), _jsx(Switch, { id: "hide-ci-status", "data-testid": "hide-ci-status-switch", checked: hideCiStatus, onCheckedChange: (v) => handleSwitchChange('hideCiStatus', setHideCiStatus, v) })] })] }), _jsx(Separator, {}), _jsxs("div", { className: "space-y-3", children: [_jsx("h3", { className: "text-sm font-semibold", children: "Stage Timeouts" }), _jsx("p", { className: "text-muted-foreground text-xs", children: "Maximum execution time per agent stage" }), _jsx("h4", { className: "text-muted-foreground text-xs font-semibold tracking-wider uppercase", children: "Feature Agent" }), FEATURE_AGENT_FIELDS.map((field) => (_jsxs("div", { className: "flex items-center justify-between gap-4", children: [_jsx(Label, { htmlFor: `stage-timeout-${field.key}`, children: field.label }), _jsx(TimeoutSlider, { id: `stage-timeout-${field.key}`, testId: `stage-timeout-${field.key}-input`, value: field.state, onChange: field.setter, onBlur: () => handleFieldBlur(field.key, field.state, field.original), defaultSeconds: field.defaultSeconds })] }, field.key))), _jsx("h4", { className: "text-muted-foreground pt-2 text-xs font-semibold tracking-wider uppercase", children: "Analyze Repository Agent" }), ANALYZE_REPO_FIELDS.map((field) => (_jsxs("div", { className: "flex items-center justify-between gap-4", children: [_jsx(Label, { htmlFor: `stage-timeout-${field.key}`, children: field.label }), _jsx(TimeoutSlider, { id: `stage-timeout-${field.key}`, testId: `stage-timeout-${field.key}-input`, value: field.state, onChange: field.setter, onBlur: () => handleFieldBlur(field.key, field.state, field.original), defaultSeconds: field.defaultSeconds })] }, field.key)))] })] })] }));
}
