import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useCallback, useEffect, useState } from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, } from "../components/ui/dialog";
import { Button } from "../components/ui/button";
import { Users, RefreshCw, AlertCircle, ServerOff } from "lucide-react";
import { checkConnectionAvailability, disconnectLicenseUser, getActiveLicenseUsers, } from "./services/editService";
import { Spinner } from "./ui/Spinner";
import { formatDistanceToNow } from "date-fns";
import { toast } from "sonner";
export function ConcurrentUserLimitDialog({ open, onOpenChange, sessionId, backendReachable: initialBackendReachable, currentUsers: initialCurrentUsers, maxUsers: initialMaxUsers, message: initialMessage, onRetry, isAdministrator = false, }) {
    const [isChecking, setIsChecking] = useState(false);
    const [isPolling, setIsPolling] = useState(false);
    const [displayCurrentUsers, setDisplayCurrentUsers] = useState(initialCurrentUsers);
    const [displayMaxUsers, setDisplayMaxUsers] = useState(initialMaxUsers);
    const [displayMessage, setDisplayMessage] = useState(initialMessage);
    const [backendReachable, setBackendReachable] = useState(initialBackendReachable);
    const [activeUsers, setActiveUsers] = useState([]);
    const [activeUsersLoading, setActiveUsersLoading] = useState(false);
    const [disconnectingUser, setDisconnectingUser] = useState(null);
    const refreshActiveUsers = useCallback(async () => {
        if (!isAdministrator || !open || !backendReachable)
            return;
        setActiveUsersLoading(true);
        try {
            const rows = await getActiveLicenseUsers();
            setActiveUsers(rows);
        }
        catch (e) {
            console.error(e);
            toast.error(e instanceof Error ? e.message : "Could not load active users");
        }
        finally {
            setActiveUsersLoading(false);
        }
    }, [isAdministrator, open, backendReachable]);
    useEffect(() => {
        if (open) {
            setDisplayCurrentUsers(initialCurrentUsers);
            setDisplayMaxUsers(initialMaxUsers);
            setDisplayMessage(initialMessage);
            setBackendReachable(initialBackendReachable);
        }
    }, [
        open,
        initialBackendReachable,
        initialCurrentUsers,
        initialMaxUsers,
        initialMessage,
    ]);
    useEffect(() => {
        if (open && isAdministrator && backendReachable) {
            void refreshActiveUsers();
        }
        else {
            setActiveUsers([]);
        }
    }, [open, isAdministrator, backendReachable, refreshActiveUsers]);
    useEffect(() => {
        if (!open) {
            setIsPolling(false);
            return;
        }
        setIsPolling(true);
        const interval = setInterval(async () => {
            try {
                const result = await checkConnectionAvailability(sessionId);
                setBackendReachable(result.backendReachable);
                if (result.currentUsers !== undefined)
                    setDisplayCurrentUsers(result.currentUsers);
                if (result.maxUsers !== undefined)
                    setDisplayMaxUsers(result.maxUsers);
                if (result.message !== undefined)
                    setDisplayMessage(result.message);
                if (isAdministrator && result.backendReachable) {
                    await refreshActiveUsers();
                }
                if (result.allowed) {
                    clearInterval(interval);
                    setIsPolling(false);
                    onRetry();
                    onOpenChange(false);
                }
            }
            catch (error) {
                console.error("Error checking connection availability:", error);
            }
        }, 7500);
        return () => {
            clearInterval(interval);
        };
    }, [
        open,
        sessionId,
        onRetry,
        onOpenChange,
        isAdministrator,
        refreshActiveUsers,
    ]);
    const handleManualRetry = async () => {
        setIsChecking(true);
        try {
            const result = await checkConnectionAvailability(sessionId);
            setBackendReachable(result.backendReachable);
            if (result.currentUsers !== undefined)
                setDisplayCurrentUsers(result.currentUsers);
            if (result.maxUsers !== undefined)
                setDisplayMaxUsers(result.maxUsers);
            if (result.message !== undefined)
                setDisplayMessage(result.message);
            if (isAdministrator && result.backendReachable) {
                await refreshActiveUsers();
            }
            if (result.allowed) {
                onRetry();
                onOpenChange(false);
            }
        }
        catch (error) {
            console.error("Error checking connection availability:", error);
        }
        finally {
            setIsChecking(false);
        }
    };
    const handleDisconnect = async (userName) => {
        setDisconnectingUser(userName);
        try {
            const { disconnected } = await disconnectLicenseUser(userName);
            toast.success(disconnected === 0
                ? "No sessions to disconnect"
                : disconnected === 1
                    ? "Disconnected 1 session"
                    : `Disconnected ${disconnected} sessions`);
            await refreshActiveUsers();
            const result = await checkConnectionAvailability(sessionId);
            setBackendReachable(result.backendReachable);
            if (result.currentUsers !== undefined)
                setDisplayCurrentUsers(result.currentUsers);
            if (result.maxUsers !== undefined)
                setDisplayMaxUsers(result.maxUsers);
            if (result.message !== undefined)
                setDisplayMessage(result.message);
            if (result.allowed) {
                onRetry();
                onOpenChange(false);
            }
        }
        catch (e) {
            toast.error(e instanceof Error ? e.message : "Disconnect failed");
        }
        finally {
            setDisconnectingUser(null);
        }
    };
    return (_jsx(Dialog, { open: open, onOpenChange: onOpenChange, children: _jsxs(DialogContent, { className: isAdministrator
                ? "flex max-h-[min(90vh,calc(100dvh-2rem))] flex-col overflow-hidden sm:max-w-[640px]"
                : "sm:max-w-[500px]", children: [_jsx(DialogHeader, { className: "shrink-0", children: _jsxs("div", { className: "flex items-start gap-4", children: [_jsx("div", { className: "bg-feedback-orange-light text-feedback-orange flex size-10 shrink-0 items-center justify-center rounded-full", children: backendReachable ? (_jsx(Users, { className: "size-5", strokeWidth: 1 })) : (_jsx(ServerOff, { className: "size-5", strokeWidth: 1 })) }), _jsxs("div", { className: "flex min-w-0 flex-1 flex-col gap-1", children: [_jsx(DialogTitle, { className: "text-xl font-bold", children: backendReachable
                                            ? "Concurrent User Limit Reached"
                                            : "Backend Not Reachable" }), _jsxs("div", { className: "text-muted-foreground mt-1 text-sm leading-relaxed", children: [_jsx("p", { className: "mb-3", children: displayMessage }), backendReachable && (_jsxs("div", { className: "text-feedback-orange bg-feedback-orange-light border-feedback-orange flex items-center gap-2 rounded-lg border p-3", children: [_jsx(AlertCircle, { strokeWidth: 1, className: "size-4 shrink-0" }), _jsxs("span", { className: "text-xs", children: ["Currently ", displayCurrentUsers, " of ", displayMaxUsers, " user slots are in use."] })] }))] })] })] }) }), isAdministrator && backendReachable && (_jsxs("div", { className: "border-border/60 mt-6 flex min-h-0 flex-1 flex-col gap-2 border-t px-6 pt-6 pb-2", children: [_jsx("p", { className: "text-foreground text-sm font-medium", children: "Active users (license seats)" }), _jsx("p", { className: "text-muted-foreground text-xs", children: "Oldest connections first. Disconnect ends that user's editor session so a seat may become available." }), activeUsersLoading && activeUsers.length === 0 ? (_jsxs("div", { className: "text-muted-foreground flex items-center gap-2 py-4 text-sm", children: [_jsx(Spinner, { className: "size-4" }), "Loading\u2026"] })) : activeUsers.length === 0 ? (_jsx("p", { className: "text-muted-foreground py-2 text-sm", children: "No active license users found." })) : (_jsx("div", { className: "min-h-0 flex-1 overflow-y-auto rounded-md border", children: _jsxs("table", { className: "w-full text-sm", children: [_jsx("thead", { className: "border-border/60 bg-muted/95 text-muted-foreground supports-[backdrop-filter]:bg-muted/80 sticky top-0 z-[1] border-b text-left text-xs backdrop-blur-sm", children: _jsxs("tr", { children: [_jsx("th", { className: "px-3 py-2 font-medium", children: "User" }), _jsx("th", { className: "w-24 px-3 py-2 font-medium", children: "Tabs" }), _jsx("th", { className: "px-3 py-2 font-medium", children: "Connected" }), _jsx("th", { className: "w-[140px] px-3 py-2 font-medium" })] }) }), _jsx("tbody", { children: activeUsers.map((row) => (_jsxs("tr", { className: "border-border/60 border-t", children: [_jsxs("td", { className: "px-3 py-2 align-top", children: [_jsx("div", { className: "text-foreground max-w-[220px] truncate font-medium", children: row.fullName?.trim() || row.userName }), row.fullName?.trim() ? (_jsx("div", { className: "text-muted-foreground max-w-[220px] truncate text-xs", children: row.userName })) : null] }), _jsx("td", { className: "text-muted-foreground px-3 py-2 align-top", children: row.connectionCount }), _jsx("td", { className: "text-muted-foreground px-3 py-2 align-top text-xs", children: row.connectedSinceUtc
                                                        ? `${formatDistanceToNow(new Date(row.connectedSinceUtc), { addSuffix: true })}`
                                                        : "—" }), _jsx("td", { className: "px-3 py-2 text-right align-top", children: _jsx(Button, { type: "button", variant: "outline", size: "sm", className: "text-destructive border-destructive/30 hover:bg-destructive/10", disabled: disconnectingUser !== null, onClick: () => void handleDisconnect(row.userName), children: disconnectingUser === row.userName ? (_jsxs(_Fragment, { children: [_jsx(Spinner, { className: "mr-1 size-3" }), "\u2026"] })) : ("Disconnect") }) })] }, row.userName))) })] }) }))] })), _jsxs(DialogFooter, { className: "mt-auto shrink-0 border-t bg-white px-6 py-4 sm:flex-row sm:justify-between", children: [_jsx("div", { className: "text-muted-foreground mb-3 flex items-center gap-2 text-xs sm:mb-0", children: isPolling && (_jsxs(_Fragment, { children: [_jsx(RefreshCw, { strokeWidth: 1, className: "size-3 animate-spin" }), _jsx("span", { children: backendReachable
                                            ? "Checking for available seats..."
                                            : "Checking backend connection..." })] })) }), _jsxs("div", { className: "flex w-full gap-2 sm:w-auto", children: [_jsx(Button, { variant: "outline", onClick: () => onOpenChange(false), disabled: isChecking, children: "Close" }), _jsx(Button, { onClick: handleManualRetry, disabled: isChecking, className: "min-w-[120px]", children: isChecking ? (_jsxs(_Fragment, { children: [_jsx(Spinner, { className: "mr-2 size-4" }), "Checking..."] })) : (_jsxs(_Fragment, { children: [_jsx(RefreshCw, { strokeWidth: 1, className: "mr-2 size-4" }), "Try Again"] })) })] })] })] }) }));
}
//# sourceMappingURL=ConcurrentUserLimitDialog.js.map