import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { memo, useEffect, useState, useRef } from 'react';
import { Copy, Check, CreditCard, Loader2, X, Key, ExternalLink, ArrowRight, } from 'lucide-react';
import { QRCodeSVG } from 'qrcode.react';
import { ProviderLogo } from '../../common/ProviderLogo';
import { useSetuStore } from '../../../stores/setuStore';
import { useSetuBalance } from '../../../hooks/useSetuBalance';
export const ProviderSetupStep = memo(function ProviderSetupStep({ authStatus, onSetupWallet, onAddProvider, onRemoveProvider, onStartOAuth, onStartOAuthManual, onExchangeOAuthCode, onOpenTopup, onNext, manageMode = false, onClose, hideHeader = false, }) {
    const [copied, setCopied] = useState(false);
    const [isSettingUp, setIsSettingUp] = useState(false);
    const [addingProvider, setAddingProvider] = useState(null);
    const [apiKeyInput, setApiKeyInput] = useState('');
    const [removingProvider, setRemovingProvider] = useState(null);
    const [confirmingDelete, setConfirmingDelete] = useState(null);
    const [oauthSession, setOauthSession] = useState(null);
    const [oauthCodeInput, setOauthCodeInput] = useState('');
    const [isExchangingCode, setIsExchangingCode] = useState(false);
    const [isOpeningPopup, setIsOpeningPopup] = useState(false);
    const balance = useSetuStore((s) => s.balance);
    const usdcBalance = useSetuStore((s) => s.usdcBalance);
    const apiKeyInputRef = useRef(null);
    const oauthCodeInputRef = useRef(null);
    useSetuBalance('setu');
    useEffect(() => {
        if (!authStatus.setu.configured && !isSettingUp) {
            setIsSettingUp(true);
            onSetupWallet().finally(() => setIsSettingUp(false));
        }
    }, [authStatus.setu.configured, onSetupWallet, isSettingUp]);
    useEffect(() => {
        if (addingProvider && apiKeyInputRef.current) {
            apiKeyInputRef.current.focus();
        }
    }, [addingProvider]);
    useEffect(() => {
        if (oauthSession && oauthCodeInputRef.current) {
            oauthCodeInputRef.current.focus();
        }
    }, [oauthSession]);
    const handleCopy = async () => {
        if (authStatus.setu.publicKey) {
            await navigator.clipboard.writeText(authStatus.setu.publicKey);
            setCopied(true);
            setTimeout(() => setCopied(false), 2000);
        }
    };
    const truncateAddress = (addr) => `${addr.slice(0, 8)}...${addr.slice(-6)}`;
    const handleAddProvider = async (providerId) => {
        if (!apiKeyInput.trim())
            return;
        try {
            await onAddProvider(providerId, apiKeyInput.trim());
            setAddingProvider(null);
            setApiKeyInput('');
        }
        catch { }
    };
    const handleRemoveProvider = async (providerId) => {
        if (confirmingDelete === providerId) {
            setRemovingProvider(providerId);
            try {
                await onRemoveProvider(providerId);
            }
            finally {
                setRemovingProvider(null);
                setConfirmingDelete(null);
            }
        }
        else {
            setConfirmingDelete(providerId);
        }
    };
    const handleCancelDelete = () => {
        setConfirmingDelete(null);
    };
    const handleStartOAuth = async (providerId, mode) => {
        if (providerId === 'anthropic') {
            setOauthSession({ provider: providerId, sessionId: null, mode });
        }
        else {
            onStartOAuth(providerId, mode);
        }
    };
    const handleOpenPopup = async () => {
        if (!oauthSession)
            return;
        setIsOpeningPopup(true);
        try {
            const { sessionId } = await onStartOAuthManual(oauthSession.provider, oauthSession.mode);
            setOauthSession({ ...oauthSession, sessionId });
        }
        catch (err) {
            console.error('Failed to start OAuth:', err);
        }
        setIsOpeningPopup(false);
    };
    const handleExchangeCode = async () => {
        if (!oauthSession || !oauthSession.sessionId || !oauthCodeInput.trim())
            return;
        setIsExchangingCode(true);
        try {
            await onExchangeOAuthCode(oauthSession.provider, oauthCodeInput.trim(), oauthSession.sessionId);
            setOauthSession(null);
            setOauthCodeInput('');
        }
        catch { }
        setIsExchangingCode(false);
    };
    const handleCancelOAuth = () => {
        setOauthSession(null);
        setOauthCodeInput('');
    };
    const configuredProviders = Object.entries(authStatus.providers).filter(([id, info]) => info.configured && id !== 'setu');
    const unconfiguredProviders = Object.entries(authStatus.providers).filter(([id, info]) => !info.configured && id !== 'setu');
    return (_jsxs("div", { className: "min-h-screen flex flex-col", children: [!hideHeader && (_jsxs("div", { className: "flex items-center justify-between px-4 sm:px-6 py-4 border-b border-border", children: [_jsxs("div", { className: "flex items-center gap-3", children: [_jsx(ProviderLogo, { provider: "setu", size: 24 }), _jsx("span", { className: "font-semibold text-foreground", children: "AGI" })] }), !manageMode && (_jsxs("div", { className: "flex items-center gap-2 text-sm text-muted-foreground", children: [_jsx("span", { className: "w-2 h-2 rounded-full bg-green-500" }), "Step 1 of 2"] }))] })), _jsx("div", { className: `flex-1 px-4 sm:px-6 lg:px-12 pb-32 ${hideHeader ? 'pt-8 sm:pt-10 lg:pt-14' : 'pt-6 sm:pt-8 lg:pt-12'}`, children: _jsxs("div", { className: "max-w-7xl mx-auto", children: [_jsxs("div", { className: "mb-10", children: [_jsx("h1", { className: "text-2xl sm:text-3xl lg:text-4xl font-semibold text-foreground mb-3", children: manageMode ? 'Manage Providers' : 'Welcome to AGI' }), _jsx("p", { className: "text-lg text-muted-foreground max-w-2xl", children: manageMode
                                        ? 'Add or remove AI providers. Your changes are saved automatically.'
                                        : "Setu is your default AI provider, powered by your wallet. Add more providers below if you'd like." })] }), _jsxs("div", { className: "grid grid-cols-1 sm:grid-cols-3 gap-6 sm:gap-8", children: [_jsx("div", { children: _jsx("div", { className: "bg-card rounded-2xl border border-border p-5", children: authStatus.setu.configured && authStatus.setu.publicKey ? (_jsxs("div", { className: "flex flex-col h-full", children: [_jsxs("div", { className: "flex items-center gap-2 px-3 py-2 bg-green-500/10 border border-green-500/20 rounded-lg", children: [_jsx(ProviderLogo, { provider: "setu", size: 16 }), _jsx("span", { className: "text-sm font-medium text-green-600 dark:text-green-400", children: "Setu" }), _jsx("span", { className: "text-xs text-green-600/60 dark:text-green-500/60 ml-auto", children: "Default Provider" })] }), _jsx("div", { className: "flex justify-center py-4 mt-4", children: _jsx("div", { className: "bg-white p-2 rounded-lg", children: _jsx(QRCodeSVG, { value: authStatus.setu.publicKey, size: 140, level: "M" }) }) }), _jsxs("div", { className: "space-y-2 mt-4", children: [_jsxs("button", { type: "button", onClick: handleCopy, className: "w-full flex items-center justify-center gap-2 px-3 py-2 bg-muted hover:bg-muted/80 rounded-lg text-xs font-mono text-muted-foreground transition-colors", children: [truncateAddress(authStatus.setu.publicKey), copied ? (_jsx(Check, { className: "w-3.5 h-3.5 text-green-500" })) : (_jsx(Copy, { className: "w-3.5 h-3.5 text-muted-foreground" }))] }), _jsxs("div", { className: "flex items-center justify-between px-3 py-2 bg-muted/50 rounded-lg", children: [_jsx("span", { className: "text-xs text-muted-foreground", children: "Balance" }), _jsxs("span", { className: "font-mono text-sm text-foreground", children: ["$", ((balance ?? 0) + (usdcBalance ?? 0)).toFixed(4)] })] })] }), _jsxs("div", { className: "flex items-center gap-4 py-4", children: [_jsx("div", { className: "flex-1 h-px bg-border" }), _jsx("span", { className: "text-xs text-muted-foreground font-medium", children: "OR" }), _jsx("div", { className: "flex-1 h-px bg-border" })] }), _jsxs("button", { type: "button", onClick: onOpenTopup, className: "w-full flex items-center justify-center gap-2 px-4 py-2.5 bg-primary text-primary-foreground rounded-lg text-sm font-medium hover:bg-primary/90 transition-colors", children: [_jsx(CreditCard, { className: "w-4 h-4" }), "Pay via Card"] })] })) : (_jsx("div", { className: "flex items-center justify-center py-16", children: _jsx(Loader2, { className: "w-8 h-8 animate-spin text-muted-foreground" }) })) }) }), _jsxs("div", { className: "sm:col-span-2 space-y-6", children: [_jsxs("div", { children: [_jsxs("div", { className: "flex items-center justify-between mb-4", children: [_jsx("h2", { className: "font-semibold text-foreground", children: "Connected Providers" }), configuredProviders.length > 0 && (_jsxs("span", { className: "text-sm text-muted-foreground", children: [configuredProviders.length, " active"] }))] }), configuredProviders.length === 0 ? (_jsx("div", { className: "text-sm text-muted-foreground py-4", children: "No providers connected yet. Add one below." })) : (_jsx("div", { className: "flex flex-wrap gap-2", children: configuredProviders.map(([id, info]) => (_jsxs("div", { className: `flex items-center gap-2 pl-3 pr-2 py-2 rounded-full transition-all duration-200 ${confirmingDelete === id
                                                            ? 'bg-destructive/10 border border-destructive/30'
                                                            : 'group bg-green-500/10 border border-green-500/20'}`, children: [_jsx(ProviderLogo, { provider: id, size: 16 }), _jsx("span", { className: `text-sm font-medium transition-colors ${confirmingDelete === id
                                                                    ? 'text-destructive'
                                                                    : 'text-green-600 dark:text-green-400'}`, children: info.label }), confirmingDelete !== id && (_jsx("span", { className: "text-xs text-green-600/60 dark:text-green-500/60", children: info.type === 'oauth' ? 'OAuth' : 'API' })), confirmingDelete === id ? (_jsxs("div", { className: "flex items-center gap-1 ml-1", children: [_jsx("span", { className: "text-xs text-destructive/80 mr-1", children: "Remove?" }), _jsx("button", { type: "button", onClick: () => handleRemoveProvider(id), disabled: removingProvider === id, className: "px-2 py-0.5 text-xs bg-destructive text-destructive-foreground rounded hover:bg-destructive/90 transition-colors disabled:opacity-50", children: removingProvider === id ? (_jsx(Loader2, { className: "w-3 h-3 animate-spin" })) : ('Yes') }), _jsx("button", { type: "button", onClick: handleCancelDelete, className: "px-2 py-0.5 text-xs bg-muted text-muted-foreground rounded hover:bg-muted/80 transition-colors", children: "No" })] })) : (id !== 'setu' && (_jsx("button", { type: "button", onClick: () => handleRemoveProvider(id), className: "ml-1 p-1 text-green-600/40 dark:text-green-500/40 hover:text-green-600/80 dark:hover:text-green-500/80 opacity-0 group-hover:opacity-100 transition-opacity", children: _jsx(X, { className: "w-3 h-3" }) })))] }, id))) }))] }), _jsxs("div", { children: [_jsx("h2", { className: "font-semibold text-foreground mb-4", children: "Add Providers" }), _jsx("div", { className: "grid grid-cols-1 sm:grid-cols-2 gap-3 items-start", children: unconfiguredProviders.map(([id, info]) => (_jsx("div", { children: addingProvider === id ? (_jsxs("div", { className: "flex items-center gap-2 p-3 bg-card border border-ring rounded-xl overflow-hidden", children: [_jsx("div", { className: "shrink-0", children: _jsx(ProviderLogo, { provider: id, size: 18 }) }), _jsx("input", { ref: apiKeyInputRef, type: "password", value: apiKeyInput, onChange: (e) => setApiKeyInput(e.target.value), placeholder: `${info.label} API key...`, className: "flex-1 min-w-0 bg-transparent text-sm outline-none placeholder:text-muted-foreground text-foreground", onKeyDown: (e) => {
                                                                        if (e.key === 'Enter')
                                                                            handleAddProvider(id);
                                                                        if (e.key === 'Escape') {
                                                                            setAddingProvider(null);
                                                                            setApiKeyInput('');
                                                                        }
                                                                    } }), _jsx("button", { type: "button", onClick: () => handleAddProvider(id), disabled: !apiKeyInput.trim(), className: "shrink-0 px-3 py-1.5 bg-primary text-primary-foreground text-sm font-medium rounded-lg disabled:opacity-50", children: "Add" }), _jsx("button", { type: "button", onClick: () => {
                                                                        setAddingProvider(null);
                                                                        setApiKeyInput('');
                                                                    }, className: "shrink-0 p-1.5 text-muted-foreground hover:text-foreground", children: _jsx(X, { className: "w-4 h-4" }) })] })) : (_jsxs("div", { className: "flex items-center justify-between p-3 bg-card border border-border hover:border-border/80 rounded-xl transition-colors gap-2", children: [_jsxs("div", { className: "flex items-center gap-3 min-w-0", children: [_jsx(ProviderLogo, { provider: id, size: 20 }), _jsxs("div", { className: "min-w-0", children: [_jsx("div", { className: "font-medium text-foreground truncate", children: info.label }), _jsxs("div", { className: "text-xs text-muted-foreground", children: [info.modelCount, " models"] })] })] }), _jsxs("div", { className: "flex items-center gap-1", children: [_jsxs("button", { type: "button", onClick: () => setAddingProvider(id), className: "flex items-center gap-1.5 px-3 py-1.5 text-sm text-muted-foreground hover:text-foreground hover:bg-muted rounded-lg transition-colors", children: [_jsx(Key, { className: "w-3.5 h-3.5" }), "API"] }), info.supportsOAuth && (_jsxs("button", { type: "button", onClick: () => handleStartOAuth(id, id === 'anthropic' ? 'max' : undefined), className: "flex items-center gap-1.5 px-3 py-1.5 text-sm text-muted-foreground hover:text-foreground hover:bg-muted rounded-lg transition-colors", children: [_jsx(ExternalLink, { className: "w-3.5 h-3.5" }), id === 'anthropic' ? 'Max' : 'OAuth'] }))] })] })) }, id))) })] })] })] })] }) }), _jsx("div", { className: "fixed bottom-0 left-0 right-0 px-4 sm:px-6 py-4 border-t border-border bg-background", children: _jsxs("div", { className: "max-w-7xl mx-auto flex items-center justify-between", children: [!manageMode && (_jsx("div", { className: "text-xs sm:text-sm text-muted-foreground hidden sm:block", children: "You can add more providers later in settings" })), manageMode ? (_jsx("button", { type: "button", onClick: onClose, className: "flex items-center gap-2 px-6 py-3 bg-primary text-primary-foreground rounded-lg font-medium hover:bg-primary/90 transition-colors ml-auto", children: "Done" })) : (_jsxs("button", { type: "button", onClick: onNext, className: "flex items-center gap-2 px-6 py-3 bg-primary text-primary-foreground rounded-lg font-medium hover:bg-primary/90 transition-colors", children: ["Continue", _jsx(ArrowRight, { className: "w-4 h-4" })] }))] }) }), oauthSession && (_jsx("div", { className: "fixed inset-0 z-[9999] flex items-center justify-center bg-black/60 backdrop-blur-sm", children: _jsxs("div", { className: "bg-background border border-border rounded-xl w-full max-w-lg mx-6 shadow-2xl", children: [_jsxs("div", { className: "flex items-center gap-3 p-6 border-b border-border", children: [_jsx(ProviderLogo, { provider: oauthSession.provider, size: 24 }), _jsxs("h3", { className: "text-lg font-semibold", children: ["Connect", ' ', authStatus.providers[oauthSession.provider]?.label ||
                                            oauthSession.provider] })] }), !oauthSession.sessionId ? (_jsxs("div", { className: "p-6", children: [_jsxs("p", { className: "text-sm text-muted-foreground mb-6", children: ["You'll be redirected to", ' ', authStatus.providers[oauthSession.provider]?.label ||
                                            oauthSession.provider, ' ', "to authorize access. After authorizing, copy the code and return here."] }), _jsxs("div", { className: "flex gap-3", children: [_jsx("button", { type: "button", onClick: handleCancelOAuth, className: "flex-1 h-11 px-4 bg-transparent border border-border text-foreground rounded-lg font-medium hover:bg-muted/50 transition-colors", children: "Cancel" }), _jsx("button", { type: "button", onClick: handleOpenPopup, disabled: isOpeningPopup, className: "flex-1 h-11 px-4 bg-foreground text-background rounded-lg font-medium hover:bg-foreground/90 transition-colors disabled:opacity-50 flex items-center justify-center gap-2", children: isOpeningPopup ? (_jsx(Loader2, { className: "w-4 h-4 animate-spin" })) : (_jsxs(_Fragment, { children: ["Continue", _jsx(ExternalLink, { className: "w-4 h-4" })] })) })] })] })) : (_jsxs("div", { className: "p-6", children: [_jsx("p", { className: "text-sm text-muted-foreground mb-4", children: "Paste the authorization code:" }), _jsx("input", { type: "text", ref: oauthCodeInputRef, value: oauthCodeInput, onChange: (e) => setOauthCodeInput(e.target.value), placeholder: "Paste code here...", className: "w-full h-11 px-4 bg-muted/50 border border-border rounded-lg text-foreground placeholder:text-muted-foreground outline-none focus:border-foreground/30 transition-colors mb-4 font-mono text-sm", onKeyDown: (e) => {
                                        if (e.key === 'Enter')
                                            handleExchangeCode();
                                        if (e.key === 'Escape')
                                            handleCancelOAuth();
                                    } }), _jsxs("div", { className: "flex gap-3", children: [_jsx("button", { type: "button", onClick: handleCancelOAuth, className: "flex-1 h-11 px-4 bg-transparent border border-border text-foreground rounded-lg font-medium hover:bg-muted/50 transition-colors", children: "Cancel" }), _jsx("button", { type: "button", onClick: handleExchangeCode, disabled: !oauthCodeInput.trim() || isExchangingCode, className: "flex-1 h-11 px-4 bg-foreground text-background rounded-lg font-medium hover:bg-foreground/90 transition-colors disabled:opacity-50 flex items-center justify-center gap-2", children: isExchangingCode ? (_jsx(Loader2, { className: "w-4 h-4 animate-spin" })) : ('Connect') })] })] }))] }) }))] }));
});
//# sourceMappingURL=ProviderSetupStep.js.map