'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState, useTransition, useRef, useEffect } from 'react';
import { Bot, Eye, EyeOff, 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 { Button } from '../../ui/button.js';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from '../../ui/select.js';
import { updateSettingsAction } from '../../../app/actions/update-settings.js';
import { AgentType, AgentAuthMethod } from '../../../../../../packages/core/src/domain/generated/output.js';
import { getAgentTypeIcon } from '../../common/feature-node/agent-type-icons.js';
const AGENT_TYPE_OPTIONS = [
    { value: AgentType.ClaudeCode, label: 'Claude Code' },
    { value: AgentType.CodexCli, label: 'Codex CLI' },
    { value: AgentType.CopilotCli, label: 'Copilot CLI' },
    { value: AgentType.Cursor, label: 'Cursor' },
    { value: AgentType.GeminiCli, label: 'Gemini CLI' },
    { value: AgentType.Cline, label: 'Cline' },
    { value: AgentType.OpenRouter, label: 'OpenRouter' },
    { value: AgentType.TogetherAi, label: 'Together AI' },
    { value: AgentType.Ollama, label: 'Ollama' },
    { value: AgentType.Aider, label: 'Aider' },
    { value: AgentType.Continue, label: 'Continue' },
    { value: AgentType.Dev, label: 'Dev' },
];
/** Agent types that only support session-based auth (no API token). */
const SESSION_ONLY_AGENTS = new Set([AgentType.CopilotCli]);
/** Agent types that require token-based auth (API key only, no CLI binary). */
const TOKEN_REQUIRED_AGENTS = new Set([AgentType.OpenRouter, AgentType.TogetherAi]);
const AUTH_METHOD_OPTIONS = [
    { value: AgentAuthMethod.Session, label: 'Session' },
    { value: AgentAuthMethod.Token, label: 'Token' },
];
export function AgentSettingsSection({ agent }) {
    const [agentType, setAgentType] = useState(agent.type);
    const [authMethod, setAuthMethod] = useState(agent.authMethod);
    const [token, setToken] = useState(agent.token ?? '');
    const [showToken, setShowToken] = useState(false);
    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 save(payload) {
        startTransition(async () => {
            const result = await updateSettingsAction(payload);
            if (!result.success) {
                toast.error(result.error ?? 'Failed to save agent settings');
            }
        });
    }
    function buildPayload(overrides = {}) {
        const merged = { type: agentType, authMethod, ...overrides };
        const result = { type: merged.type, authMethod: merged.authMethod };
        if (merged.authMethod === AgentAuthMethod.Token) {
            result.token = overrides.token ?? token;
        }
        return { agent: result };
    }
    function handleAgentTypeChange(value) {
        const newType = value;
        let newAuthMethod = authMethod;
        if (SESSION_ONLY_AGENTS.has(newType)) {
            newAuthMethod = AgentAuthMethod.Session;
        }
        else if (TOKEN_REQUIRED_AGENTS.has(newType)) {
            newAuthMethod = AgentAuthMethod.Token;
        }
        setAgentType(newType);
        if (newAuthMethod !== authMethod) {
            setAuthMethod(newAuthMethod);
        }
        save(buildPayload({ type: newType, authMethod: newAuthMethod }));
    }
    function handleAuthMethodChange(value) {
        setAuthMethod(value);
        save(buildPayload({ authMethod: value }));
    }
    function handleTokenBlur() {
        if (token !== (agent.token ?? '')) {
            save(buildPayload({ token }));
        }
    }
    return (_jsxs(Card, { id: "agent", className: "scroll-mt-6", "data-testid": "agent-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(Bot, { className: "text-muted-foreground h-4 w-4" }), _jsx(CardTitle, { children: "Preferred Agent" })] }), 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: "Choose your AI coding agent and authentication method" })] }), _jsxs(CardContent, { className: "space-y-4", children: [_jsxs("div", { className: "space-y-2", children: [_jsx(Label, { htmlFor: "agent-type", children: "Agent Type" }), _jsxs(Select, { value: agentType, onValueChange: handleAgentTypeChange, children: [_jsx(SelectTrigger, { id: "agent-type", "data-testid": "agent-type-select", children: _jsx(SelectValue, {}) }), _jsx(SelectContent, { children: AGENT_TYPE_OPTIONS.map((opt) => {
                                            const Icon = getAgentTypeIcon(opt.value);
                                            return (_jsx(SelectItem, { value: opt.value, children: _jsxs("span", { className: "flex items-center gap-2", children: [_jsx(Icon, { className: "h-4 w-4 shrink-0" }), opt.label] }) }, opt.value));
                                        }) })] })] }), _jsxs("div", { className: "space-y-2", children: [_jsx(Label, { htmlFor: "auth-method", children: "Authentication Method" }), _jsxs(Select, { value: authMethod, onValueChange: handleAuthMethodChange, disabled: SESSION_ONLY_AGENTS.has(agentType) || TOKEN_REQUIRED_AGENTS.has(agentType), children: [_jsx(SelectTrigger, { id: "auth-method", "data-testid": "auth-method-select", children: _jsx(SelectValue, {}) }), _jsx(SelectContent, { children: AUTH_METHOD_OPTIONS.filter((opt) => {
                                            if (SESSION_ONLY_AGENTS.has(agentType))
                                                return opt.value === AgentAuthMethod.Session;
                                            if (TOKEN_REQUIRED_AGENTS.has(agentType))
                                                return opt.value === AgentAuthMethod.Token;
                                            return true;
                                        }).map((opt) => (_jsx(SelectItem, { value: opt.value, children: opt.label }, opt.value))) })] }), SESSION_ONLY_AGENTS.has(agentType) && (_jsxs("p", { className: "text-muted-foreground text-xs", children: ["Copilot CLI uses GitHub OAuth \u2014 authenticate with", ' ', _jsx("code", { className: "font-mono", children: "copilot auth login" }), ". No API token needed."] })), TOKEN_REQUIRED_AGENTS.has(agentType) && (_jsx("p", { className: "text-muted-foreground text-xs", children: "This provider requires an API key for authentication. No CLI binary needed." }))] }), authMethod === AgentAuthMethod.Token && (_jsxs("div", { className: "space-y-2", children: [_jsx(Label, { htmlFor: "agent-token", children: "API Token" }), _jsxs("div", { className: "relative", children: [_jsx(Input, { id: "agent-token", "data-testid": "agent-token-input", type: showToken ? 'text' : 'password', value: token, onChange: (e) => setToken(e.target.value), onBlur: handleTokenBlur, placeholder: "Enter your API token", className: "pe-10" }), _jsx(Button, { type: "button", variant: "ghost", size: "sm", className: "absolute top-0 right-0 h-full px-3 hover:bg-transparent", onClick: () => setShowToken(!showToken), "data-testid": "toggle-token-visibility", "aria-label": showToken ? 'Hide token' : 'Show token', children: showToken ? _jsx(EyeOff, { className: "h-4 w-4" }) : _jsx(Eye, { className: "h-4 w-4" }) })] }), _jsx("p", { className: "text-muted-foreground text-xs", children: "Saves automatically when you leave the field" })] }))] })] }));
}
