import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useCallback, useEffect, useMemo, useState } from "react";
import { AlertTriangle, CheckCircle2, CircleSlash, Key, RefreshCw, Users, } from "lucide-react";
import { DeleteIcon } from "../../../components/ui/delete-icon";
import { Button } from "../../../components/ui/button";
import { Alert, AlertDescription, AlertTitle, } from "../../../components/ui/alert";
import { SettingsPanelLayout } from "../SettingsPanelLayout";
import { useEditContext } from "../../client/editContext";
import { LoadingState } from "../../ui/LoadingState";
import { deleteStaleClusterInstance, getClusterInstances, } from "../../services/systemService";
function formatDate(value) {
    if (!value)
        return "Never";
    const date = new Date(value);
    if (Number.isNaN(date.getTime()))
        return value;
    return date.toLocaleString();
}
function statusClasses(instance) {
    if (!instance.isLive)
        return "border-border-default bg-neutral-grey-5 text-neutral-grey-50";
    if (!instance.isRoutable)
        return "border-feedback-orange bg-feedback-orange-light text-feedback-orange";
    return "border-feedback-green bg-feedback-green-light text-feedback-green";
}
function statusLabel(instance) {
    if (!instance.isLive)
        return "Stale";
    if (!instance.isRoutable)
        return "Needs URL";
    return "Routable";
}
export function ClusterInstancesPanel() {
    const editContext = useEditContext();
    const [state, setState] = useState("idle");
    const [error, setError] = useState();
    const [data, setData] = useState();
    const [deletingInstanceId, setDeletingInstanceId] = useState();
    const load = useCallback(async () => {
        setState("loading");
        setError(undefined);
        const result = await getClusterInstances();
        if (result.type !== "success" || !result.data) {
            setState("error");
            setError(result.details || result.summary || "Failed to load cluster instances.");
            return;
        }
        setData(result.data);
        setState("success");
    }, []);
    useEffect(() => {
        void load();
    }, [load]);
    const handleDeleteStaleInstance = useCallback((instance) => {
        editContext?.confirm({
            header: "Delete stale instance",
            message: (_jsxs("span", { children: ["Delete stale cluster instance", " ", _jsx("strong", { className: "break-all", children: instance.instanceId }), " from the database? This removes its registry row and stale session routing data."] })),
            acceptLabel: "Delete",
            showCancel: true,
            accept: async () => {
                setDeletingInstanceId(instance.instanceId);
                setError(undefined);
                const result = await deleteStaleClusterInstance(instance.instanceId);
                if (result.type !== "success") {
                    setError(result.details ||
                        result.summary ||
                        "Failed to delete stale cluster instance.");
                    setDeletingInstanceId(undefined);
                    return;
                }
                await load();
                setDeletingInstanceId(undefined);
            },
        });
    }, [editContext, load]);
    const instances = data?.instances ?? [];
    const routableCount = useMemo(() => instances.filter((instance) => instance.isRoutable).length, [instances]);
    const totalSessions = useMemo(() => instances.reduce((sum, instance) => sum +
        (instance.connectedSessionCount ?? instance.sessions?.length ?? 0), 0), [instances]);
    return (_jsxs(SettingsPanelLayout, { contentClassName: "flex flex-col gap-4", children: [_jsx("div", { className: "rounded-lg bg-white p-4 md:p-6", children: _jsxs("div", { className: "grid gap-4 md:grid-cols-3", children: [_jsx(SummaryCard, { label: "Registered", value: instances.length }), _jsx(SummaryCard, { label: "Routable", value: routableCount, tone: "success" }), _jsx(SummaryCard, { label: "Connected sessions", value: totalSessions })] }) }), state === "error" && (_jsx("div", { className: "border-feedback-red bg-feedback-red-light text-feedback-red rounded-lg border p-4 text-sm", children: error })), state === "loading" && !data && (_jsx(LoadingState, { variant: "inline", message: "Loading cluster instances...", spinnerSize: "sm" })), state !== "loading" && instances.length === 0 && !error && (_jsxs("div", { className: "border-border-default bg-neutral-grey-5 rounded-lg border p-6 text-center", children: [_jsx(CircleSlash, { className: "text-neutral-grey-50 mx-auto mb-3 h-8 w-8", strokeWidth: 1.5 }), _jsx("p", { className: "text-neutral-grey-50 text-sm", children: "No instances have registered yet. The current instance should appear after the next heartbeat." })] })), instances.length > 0 && (_jsx("div", { className: "space-y-3", children: instances.map((instance) => (_jsx(InstanceCard, { instance: instance, deleting: deletingInstanceId === instance.instanceId, onDeleteStale: () => handleDeleteStaleInstance(instance) }, instance.instanceId))) }))] }));
}
function SummaryCard({ label, value, tone = "default", }) {
    const toneClass = tone === "success"
        ? "text-feedback-green"
        : tone === "warning"
            ? "text-feedback-orange"
            : "text-neutral-grey-100";
    return (_jsxs("div", { className: "bg-neutral-grey-5 rounded-lg p-4", children: [_jsx("div", { className: "text-neutral-grey-50 text-sm", children: label }), _jsx("div", { className: `mt-1 text-sm font-medium ${toneClass}`, children: value })] }));
}
function InstanceCard({ instance, deleting, onDeleteStale, }) {
    const warnings = instance.warnings ?? [];
    const sessions = instance.sessions ?? [];
    const sessionCount = instance.connectedSessionCount ?? sessions.length;
    const canDelete = !instance.isCurrent && !instance.isLive;
    return (_jsxs("div", { className: "border-border-default rounded-lg border bg-white p-5", children: [_jsxs("div", { className: "flex flex-col gap-3 md:flex-row md:items-start md:justify-between", children: [_jsxs("div", { className: "min-w-0", children: [_jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [_jsx("h4", { className: "text-neutral-grey-100 text-sm font-medium break-all", children: instance.instanceId }), instance.isCurrent && (_jsx("span", { className: "rounded-badge bg-feedback-blue-light badge-pad-sm text-2xs text-feedback-blue font-medium", children: "Current" }))] }), _jsxs("dl", { className: "mt-3 grid gap-3 text-sm md:grid-cols-2", children: [_jsx(Field, { label: "Type", value: instance.type || "cm" }), _jsx(Field, { label: "Machine", value: instance.lastSeenMachineName || "-" }), _jsx(Field, { label: "Last heartbeat", value: formatDate(instance.lastHeartbeatUtc) }), _jsx(Field, { label: "Internal URL", value: instance.baseUrl || "Missing" })] })] }), _jsxs("div", { className: "flex shrink-0 items-center gap-2", children: [_jsxs("span", { className: `rounded-badge badge-pad text-2xs inline-flex items-center gap-1.5 border font-medium ${statusClasses(instance)}`, children: [instance.isRoutable ? (_jsx(CheckCircle2, { className: "h-3.5 w-3.5", strokeWidth: 1.5 })) : (_jsx(AlertTriangle, { className: "h-3.5 w-3.5", strokeWidth: 1.5 })), statusLabel(instance)] }), canDelete && (_jsxs(Button, { type: "button", variant: "outline", size: "sm", onClick: onDeleteStale, disabled: deleting, title: "Delete stale instance", children: [deleting ? (_jsx(RefreshCw, { className: "h-4 w-4 animate-spin", strokeWidth: 1.5 })) : (_jsx(DeleteIcon, { size: "lg" })), "Delete"] }))] })] }), warnings.length > 0 && (_jsxs(Alert, { variant: "warning", className: "mt-4", children: [_jsx(AlertTriangle, { className: "h-3.5 w-3.5", strokeWidth: 1.5 }), _jsxs("div", { children: [_jsx(AlertTitle, { className: "text-xs tracking-wide", children: "Warnings" }), _jsx(AlertDescription, { children: _jsx("ul", { className: "space-y-1", children: warnings.map((warning) => (_jsx("li", { children: warning }, warning))) }) })] })] })), _jsx(SessionsList, { sessions: sessions, count: sessionCount })] }));
}
function SessionsList({ sessions, count, }) {
    return (_jsxs("div", { className: "border-border-default bg-neutral-grey-5 mt-4 rounded-md border p-3", children: [_jsxs("div", { className: "text-neutral-grey-50 mb-2 flex items-center gap-2 text-xs font-medium tracking-wide", children: [_jsx(Users, { className: "h-3.5 w-3.5", strokeWidth: 1.5 }), "Connected sessions", _jsx("span", { className: "rounded-badge badge-pad-sm text-2xs text-neutral-grey-100 ring-border-default bg-white font-medium ring-1 ring-inset", children: count })] }), sessions.length === 0 ? (_jsx("p", { className: "text-neutral-grey-50 text-xs", children: "No active sessions are connected to this instance." })) : (_jsx("ul", { className: "divide-border-default divide-y", children: sessions.map((session) => (_jsxs("li", { className: "flex flex-col gap-1 py-2 text-sm md:flex-row md:items-center md:justify-between", children: [_jsxs("div", { className: "min-w-0 flex-1", children: [_jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [_jsx("span", { className: "text-neutral-grey-100 font-medium break-all", children: session.userId || "(anonymous)" }), session.consumesLicenseSeat && (_jsxs("span", { className: "rounded-badge bg-feedback-blue-light badge-pad-sm text-2xs text-feedback-blue inline-flex items-center gap-1 font-medium", children: [_jsx(Key, { className: "h-3 w-3", strokeWidth: 1.5 }), "License seat"] })), session.connectionState &&
                                            session.connectionState.toLowerCase() !== "active" && (_jsx("span", { className: "rounded-badge bg-neutral-grey-10 badge-pad-sm text-2xs text-neutral-grey-100 font-medium", children: session.connectionState }))] }), _jsx("div", { className: "text-neutral-grey-50 mt-0.5 font-mono text-[11px] break-all", children: session.sessionId })] }), _jsxs("div", { className: "text-neutral-grey-50 text-right text-xs md:ml-3 md:shrink-0", children: [_jsx("div", { className: "text-neutral-grey-50 text-[10px] tracking-wide", children: "Last heartbeat" }), _jsx("div", { children: formatDate(session.lastHeartbeatUtc) })] })] }, session.sessionId))) }))] }));
}
function Field({ label, value }) {
    return (_jsxs("div", { children: [_jsx("dt", { className: "text-neutral-grey-50 text-xs font-medium tracking-wide", children: label }), _jsx("dd", { className: "text-neutral-grey-100 mt-1 break-all", children: value })] }));
}
//# sourceMappingURL=ClusterInstancesPanel.js.map