"use client";
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useCallback, useEffect, useRef, useState } from "react";
import { cn } from "@stigmer/theme";
import { useMcpServer } from "./useMcpServer";
import { useMcpServerCredentials } from "./useMcpServerCredentials";
import { useMcpServerOAuthConnect } from "./useMcpServerOAuthConnect";
import { useMcpServerConnect } from "./useMcpServerConnect";
import { useDisconnectOAuth } from "./useDisconnectOAuth";
import { EnvVarForm } from "../environment/EnvVarForm";
import { ErrorMessage } from "../error/ErrorMessage";
/**
 * Modal dialog for connecting to an MCP server.
 *
 * Fetches the server, determines whether credentials or OAuth are
 * needed, and walks the user through the connect flow — all without
 * navigating away from the current page.
 *
 * Uses the native `<dialog>` element for accessibility (focus trap,
 * Escape to close, backdrop click).
 *
 * Built on existing hooks: {@link useMcpServer},
 * {@link useMcpServerCredentials}, {@link useMcpServerOAuthConnect},
 * and {@link useMcpServerConnect}.
 *
 * @example
 * ```tsx
 * const [connectTarget, setConnectTarget] = useState<{ org: string; slug: string } | null>(null);
 *
 * <McpServerConnectDialog
 *   org={connectTarget?.org ?? ""}
 *   slug={connectTarget?.slug ?? ""}
 *   open={connectTarget !== null}
 *   onClose={() => setConnectTarget(null)}
 *   onConnected={(name) => toast(`Connected to ${name}`)}
 * />
 * ```
 */
export function McpServerConnectDialog({ org, slug, activeOrg, open, onClose, onConnected, className, }) {
    const dialogRef = useRef(null);
    const resolvedOrg = activeOrg || org;
    useEffect(() => {
        const dialog = dialogRef.current;
        if (!dialog)
            return;
        if (open && !dialog.open) {
            dialog.showModal();
        }
        else if (!open && dialog.open) {
            dialog.close();
        }
    }, [open]);
    const handleDialogClose = useCallback(() => {
        onClose();
    }, [onClose]);
    const handleBackdropClick = useCallback((e) => {
        if (e.target === dialogRef.current) {
            onClose();
        }
    }, [onClose]);
    if (!open)
        return null;
    return (_jsx("dialog", { ref: dialogRef, onClose: handleDialogClose, onClick: handleBackdropClick, className: cn("m-auto max-h-[85vh] w-full max-w-md overflow-visible rounded-lg border border-border bg-card p-0 text-foreground shadow-lg", "backdrop:bg-black/50", className), children: _jsx("div", { className: "flex max-h-[85vh] flex-col overflow-y-auto p-6", onClick: (e) => e.stopPropagation(), children: _jsx(ConnectDialogContent, { org: org, slug: slug, activeOrg: resolvedOrg, onClose: onClose, onConnected: onConnected }) }) }));
}
function ConnectDialogContent({ org, slug, activeOrg, onClose, onConnected, }) {
    const { mcpServer, isLoading: isServerLoading, error: serverError } = useMcpServer(org, slug);
    const creds = useMcpServerCredentials(activeOrg, mcpServer);
    const { connect, isConnecting, error: connectError, clearError: clearConnectError } = useMcpServerConnect();
    const oauth = useMcpServerOAuthConnect();
    const disconnect = useDisconnectOAuth();
    const [phase, setPhase] = useState("credentials");
    const serverName = mcpServer?.metadata?.name ?? slug;
    const serverId = mcpServer?.metadata?.id ?? "";
    const declaredEnvKeys = Object.keys(mcpServer?.spec?.env ?? {});
    const handleConnect = useCallback(async () => {
        if (!serverId)
            return;
        setPhase("connecting");
        try {
            await connect(serverId, activeOrg, undefined, declaredEnvKeys);
            setPhase("success");
            onConnected?.(serverName);
        }
        catch {
            setPhase("error");
        }
    }, [serverId, activeOrg, declaredEnvKeys, connect, onConnected, serverName]);
    const handleCredentialSubmit = useCallback(async (values) => {
        await creds.saveCredentials(values);
        creds.refetch();
    }, [creds]);
    const handleOAuthSignIn = useCallback(() => {
        if (!serverId)
            return;
        oauth.startOAuth(serverId, activeOrg, declaredEnvKeys).then(() => {
            creds.refetch();
            setPhase("success");
            onConnected?.(serverName);
        }, () => {
            setPhase("error");
        });
    }, [serverId, activeOrg, declaredEnvKeys, oauth, creds, onConnected, serverName]);
    // Auto-trigger connect when credentials become ready (manual-only servers)
    useEffect(() => {
        if (phase === "credentials" &&
            creds.isReady &&
            !creds.isLoading &&
            mcpServer &&
            creds.authMode === "manual") {
            // Don't auto-connect; let user click the button
        }
    }, [phase, creds.isReady, creds.isLoading, mcpServer, creds.authMode]);
    if (isServerLoading || creds.isLoading) {
        return (_jsxs(_Fragment, { children: [_jsx(DialogHeader, { title: "Connect MCP Server", onClose: onClose }), _jsxs("div", { className: "flex flex-col items-center gap-3 py-8", children: [_jsx(LoadingSpinner, {}), _jsx("p", { className: "text-sm text-muted-foreground", children: "Loading server details..." })] })] }));
    }
    if (serverError) {
        return (_jsxs(_Fragment, { children: [_jsx(DialogHeader, { title: "Connect MCP Server", onClose: onClose }), _jsx("div", { className: "py-4", children: _jsx(ErrorMessage, { error: serverError }) })] }));
    }
    if (!mcpServer) {
        return (_jsxs(_Fragment, { children: [_jsx(DialogHeader, { title: "Connect MCP Server", onClose: onClose }), _jsx("p", { className: "py-4 text-sm text-muted-foreground", children: "MCP server not found." })] }));
    }
    if (phase === "success") {
        return (_jsxs(_Fragment, { children: [_jsx(DialogHeader, { title: "Connected", onClose: onClose }), _jsxs("div", { className: "flex flex-col items-center gap-3 py-6", children: [_jsx(SuccessIcon, {}), _jsxs("p", { className: "text-sm font-medium text-foreground", children: ["Successfully connected to ", serverName] }), _jsx("p", { className: "text-xs text-muted-foreground", children: "Tools and capabilities have been discovered." }), _jsx("button", { type: "button", onClick: onClose, className: cn("mt-2 inline-flex items-center rounded-md px-4 py-2 text-sm font-medium", "bg-primary text-primary-foreground", "hover:bg-primary-hover", "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"), children: "Done" })] })] }));
    }
    const isConnectingPhase = phase === "connecting" || isConnecting || oauth.isInProgress;
    const activeError = connectError ?? oauth.error;
    return (_jsxs(_Fragment, { children: [_jsx(DialogHeader, { title: serverName, onClose: onClose }), mcpServer.spec?.description && (_jsx("p", { className: "mb-4 text-xs leading-relaxed text-muted-foreground", children: mcpServer.spec.description })), activeError && (_jsx("div", { className: "mb-4", children: _jsx(ErrorMessage, { error: activeError, retry: () => {
                        clearConnectError();
                        oauth.clearError();
                        setPhase("credentials");
                    } }) })), creds.authMode === "oauth" && !creds.manualOverride && (_jsx(OAuthSection, { isConnected: creds.isOAuthConnected, phase: oauth.phase, onSignIn: handleOAuthSignIn, isVendorApprovalBlocked: creds.isVendorApprovalBlocked, onSwitchToManual: () => creds.setManualOverride(true), disabled: isConnectingPhase })), creds.missingVariables.length > 0 && (_jsx("div", { className: "mt-2", children: _jsx(EnvVarForm, { variables: creds.missingVariables, onSubmit: (values) => handleCredentialSubmit(values), isSubmitting: creds.isSaving, disabled: isConnectingPhase, hideSaveToggle: true }) })), creds.authMode === "oauth" && creds.manualOverride && (_jsx("button", { type: "button", onClick: () => creds.setManualOverride(false), disabled: isConnectingPhase, className: "mt-2 text-xs text-muted-foreground underline hover:text-foreground", children: "Sign in with OAuth instead" })), creds.isReady && creds.authMode === "manual" && (_jsxs("button", { type: "button", onClick: handleConnect, disabled: isConnectingPhase, className: cn("mt-4 inline-flex w-full items-center justify-center gap-2 rounded-md px-4 py-2 text-sm font-medium", "bg-primary text-primary-foreground", "hover:bg-primary-hover", "disabled:pointer-events-none disabled:opacity-50", "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"), children: [isConnectingPhase && _jsx(LoadingSpinner, { size: "sm" }), isConnectingPhase ? "Connecting..." : "Connect"] })), creds.isReady && creds.authMode === "oauth" && creds.isOAuthConnected && (_jsxs("button", { type: "button", onClick: handleConnect, disabled: isConnectingPhase, className: cn("mt-4 inline-flex w-full items-center justify-center gap-2 rounded-md px-4 py-2 text-sm font-medium", "bg-primary text-primary-foreground", "hover:bg-primary-hover", "disabled:pointer-events-none disabled:opacity-50", "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"), children: [isConnectingPhase && _jsx(LoadingSpinner, { size: "sm" }), isConnectingPhase ? "Discovering tools..." : "Discover Tools"] })), !creds.isReady &&
                creds.missingVariables.length === 0 &&
                creds.authMode === "manual" && (_jsx("p", { className: "mt-4 text-center text-xs text-muted-foreground", children: "No credentials required \u2014 this server is ready to connect." }))] }));
}
// ---------------------------------------------------------------------------
// Sub-components
// ---------------------------------------------------------------------------
function DialogHeader({ title, onClose, }) {
    return (_jsxs("div", { className: "mb-4 flex items-start justify-between gap-3", children: [_jsx("h2", { className: "text-base font-semibold text-foreground", children: title }), _jsx("button", { type: "button", onClick: onClose, "aria-label": "Close", className: "inline-flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-accent-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring", children: _jsx(CloseIcon, {}) })] }));
}
function OAuthSection({ isConnected, phase, onSignIn, isVendorApprovalBlocked, onSwitchToManual, disabled, }) {
    if (isConnected) {
        return (_jsxs("div", { className: "flex items-center gap-2 rounded-md border border-border bg-muted-faint px-3 py-2", children: [_jsx("span", { className: "size-2 shrink-0 rounded-full bg-green-500" }), _jsx("span", { className: "text-sm text-foreground", children: "OAuth connected" })] }));
    }
    const isInProgress = phase !== "idle" && phase !== "done";
    const phaseLabel = {
        initiating: "Starting OAuth...",
        "awaiting-callback": "Waiting for authorization...",
        completing: "Completing OAuth...",
        connecting: "Discovering tools...",
    };
    return (_jsxs("div", { className: "flex flex-col gap-2", children: [_jsxs("button", { type: "button", onClick: onSignIn, disabled: disabled || isInProgress || isVendorApprovalBlocked, className: cn("inline-flex w-full items-center justify-center gap-2 rounded-md px-4 py-2 text-sm font-medium", "bg-primary text-primary-foreground", "hover:bg-primary-hover", "disabled:pointer-events-none disabled:opacity-50", "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"), children: [isInProgress && _jsx(LoadingSpinner, { size: "sm" }), isInProgress ? (phaseLabel[phase] ?? "Connecting...") : "Sign in with OAuth"] }), isVendorApprovalBlocked && (_jsx("p", { className: "text-xs text-muted-foreground", children: "OAuth sign-in is pending vendor approval. You can enter your token manually instead." })), _jsx("button", { type: "button", onClick: onSwitchToManual, disabled: disabled || isInProgress, className: "text-xs text-muted-foreground underline hover:text-foreground", children: "Enter token manually" })] }));
}
function LoadingSpinner({ size = "md" }) {
    const cls = size === "sm" ? "size-3.5" : "size-5";
    return (_jsxs("svg", { className: cn(cls, "animate-spin text-current"), viewBox: "0 0 24 24", fill: "none", "aria-hidden": "true", children: [_jsx("circle", { cx: "12", cy: "12", r: "10", stroke: "currentColor", strokeWidth: "3", strokeLinecap: "round", className: "opacity-25" }), _jsx("path", { d: "M12 2a10 10 0 0 1 10 10", stroke: "currentColor", strokeWidth: "3", strokeLinecap: "round", className: "opacity-75" })] }));
}
function SuccessIcon() {
    return (_jsxs("svg", { className: "size-10 text-green-500", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: [_jsx("circle", { cx: "12", cy: "12", r: "10" }), _jsx("path", { d: "m9 12 2 2 4-4" })] }));
}
function CloseIcon() {
    return (_jsx("svg", { className: "size-4", viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: _jsx("path", { d: "m4 4 8 8M12 4l-8 8" }) }));
}
//# sourceMappingURL=McpServerConnectDialog.js.map