'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
/**
 * GitHub Integration settings section.
 *
 * Stores a single Personal Access Token (encrypted at rest via LocalSecretBox).
 * When set, every new terminal session shep spawns gets GH_TOKEN /
 * GITHUB_TOKEN injected automatically — so `gh`, `git push`, etc. authenticate
 * without the user having to run `gh auth login` interactively.
 *
 * The token is only sent to the server once (on Connect). After that, the
 * client only ever knows whether one is stored, never its value.
 */
import { useEffect, useState, useTransition } from 'react';
import { Eye, EyeOff, CheckCircle2, ExternalLink } from 'lucide-react';
import { toast } from 'sonner';
import { Input } from '../../ui/input.js';
import { Button } from '../../ui/button.js';
import { Label } from '../../ui/label.js';
import { connectGithubAction, disconnectGithubAction, getGithubStatusAction, } from '../../../app/actions/github-integration.js';
const PAT_DOCS_URL = 'https://github.com/settings/tokens?type=beta';
export function GithubIntegrationSection() {
    const [status, setStatus] = useState(null);
    const [token, setToken] = useState('');
    const [showToken, setShowToken] = useState(false);
    const [isPending, startTransition] = useTransition();
    useEffect(() => {
        let cancelled = false;
        void getGithubStatusAction()
            .then((s) => {
            if (!cancelled)
                setStatus(s);
        })
            .catch(() => {
            if (!cancelled)
                setStatus({ connected: false, connectedAt: null, updatedAt: null });
        });
        return () => {
            cancelled = true;
        };
    }, []);
    function handleConnect() {
        const trimmed = token.trim();
        if (!trimmed) {
            toast.error('Paste a GitHub Personal Access Token first');
            return;
        }
        startTransition(async () => {
            const result = await connectGithubAction(trimmed);
            if (result.success) {
                toast.success(`Connected to GitHub${result.login ? ` as @${result.login}` : ''}`);
                setToken('');
                setShowToken(false);
                const next = await getGithubStatusAction();
                setStatus(next);
            }
            else {
                toast.error(result.error ?? 'Failed to connect to GitHub');
            }
        });
    }
    function handleDisconnect() {
        startTransition(async () => {
            const result = await disconnectGithubAction();
            if (result.success) {
                toast.success('GitHub disconnected');
                const next = await getGithubStatusAction();
                setStatus(next);
            }
            else {
                toast.error(result.error ?? 'Failed to disconnect');
            }
        });
    }
    if (status === null) {
        return (_jsx("div", { className: "text-muted-foreground py-4 text-xs", "data-testid": "github-integration-loading", children: "Checking GitHub integration\u2026" }));
    }
    if (status.connected) {
        return (_jsxs("div", { className: "space-y-3 py-3", "data-testid": "github-integration-connected", children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx(CheckCircle2, { className: "h-4 w-4 text-emerald-500" }), _jsx("span", { className: "text-sm", children: "Connected" }), status.updatedAt ? (_jsxs("span", { className: "text-muted-foreground text-[11px]", children: ["\u00B7 last updated ", new Date(status.updatedAt).toLocaleDateString()] })) : null] }), _jsxs("p", { className: "text-muted-foreground text-[11px] leading-relaxed", children: ["Every terminal opened in shep now has ", _jsx("code", { children: "GH_TOKEN" }), " and ", _jsx("code", { children: "GITHUB_TOKEN" }), ' ', "set automatically. ", _jsx("code", { children: "gh" }), ", ", _jsx("code", { children: "git push" }), ", and other tools that read those env vars will authenticate as your GitHub user."] }), _jsx("div", { className: "flex items-center gap-2", children: _jsx(Button, { variant: "outline", size: "sm", onClick: handleDisconnect, disabled: isPending, "data-testid": "github-disconnect-button", children: isPending ? 'Disconnecting…' : 'Disconnect' }) })] }));
    }
    return (_jsxs("div", { className: "space-y-3 py-3", "data-testid": "github-integration-disconnected", children: [_jsxs("div", { className: "space-y-1.5", children: [_jsx(Label, { htmlFor: "github-pat", className: "text-xs", children: "Personal Access Token" }), _jsxs("div", { className: "flex gap-2", children: [_jsxs("div", { className: "relative flex-1", children: [_jsx(Input, { id: "github-pat", "data-testid": "github-pat-input", type: showToken ? 'text' : 'password', value: token, onChange: (e) => setToken(e.target.value), placeholder: "github_pat_\u2026 or ghp_\u2026", autoComplete: "off", className: "pr-9 font-mono text-xs", disabled: isPending }), _jsx("button", { type: "button", onClick: () => setShowToken((v) => !v), className: "text-muted-foreground hover:text-foreground absolute top-1/2 right-2 -translate-y-1/2", "aria-label": showToken ? 'Hide token' : 'Show token', tabIndex: -1, children: showToken ? _jsx(EyeOff, { className: "h-3.5 w-3.5" }) : _jsx(Eye, { className: "h-3.5 w-3.5" }) })] }), _jsx(Button, { size: "sm", onClick: handleConnect, disabled: isPending || !token.trim(), "data-testid": "github-connect-button", children: isPending ? 'Connecting…' : 'Connect' })] })] }), _jsxs("p", { className: "text-muted-foreground text-[11px] leading-relaxed", children: ["Create a fine-grained PAT with ", _jsx("code", { children: "contents: read/write" }), " and", ' ', _jsx("code", { children: "pull requests: read/write" }), " on the repos you want shep to access. Token is encrypted at rest and never leaves this machine."] }), _jsxs("a", { href: PAT_DOCS_URL, target: "_blank", rel: "noopener noreferrer", className: "text-muted-foreground hover:text-foreground inline-flex items-center gap-1 text-[11px] transition-colors", children: [_jsx(ExternalLink, { className: "h-3 w-3" }), "Generate a token on github.com"] })] }));
}
