import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useUserSession } from "@vertesia/ui/session";
import { PrincipalType } from "@vertesia/common";
import { Avatar, Table, Popover, PopoverContent, PopoverTrigger, useFetch } from "@vertesia/ui/core";
import { Users } from "lucide-react";
//TODO use a real cache
const USER_CACHE = {};
const GROUP_CACHE = {};
/**
 * Fetch the user information given a user reference.
 * The reference has the format: `type:id`. A special reference `system` is used to refer to the system user.
 * @param userRef
 */
export function useFetchUserInfo(userId) {
    const { client } = useUserSession();
    return useFetch(() => {
        let user = USER_CACHE[userId];
        if (!user) {
            user = client.users.retrieve(userId).then(user => {
                return user;
            });
            USER_CACHE[userId] = user;
        }
        return user;
    }, [userId]);
}
/**
 * Fetch the group information given a group ID.
 * @param groupId
 */
export function useFetchGroupInfo(groupId) {
    const { client } = useUserSession();
    return useFetch(() => {
        let group = GROUP_CACHE[groupId];
        if (!group) {
            group = client.iam.groups.retrieve(groupId).then(group => {
                return group;
            });
            GROUP_CACHE[groupId] = group;
        }
        return group;
    }, [groupId]);
}
function AvatarPlaceholder() {
    return _jsx("div", { className: 'size-8' });
}
function SystemAvatar({ showTitle = false, size = "md" }) {
    return (_jsx(UserPopoverPanel, { title: "System User", description: "The system user is used to initialize built-in objects.", children: _jsxs("div", { className: "flex gap-2 items-center", children: [_jsx(Avatar, { src: "/icon.svg", size: size }), showTitle && _jsx("div", { className: "text-sm font-semibold pl-2", children: "System User" })] }) }));
}
function ServiceAccountAvatar({ accountId, showTitle = false, size = "md" }) {
    const description = (_jsxs(_Fragment, { children: [_jsx("div", { children: "This user is used by robots like workflow workers." }), _jsxs("div", { className: "text-gray-800 dark:text-gray-500 text-sm", children: [_jsx("span", { className: "font-semibold", children: "ID:" }), " ", accountId] })] }));
    return (_jsx(UserPopoverPanel, { title: "Service Account", description: description, children: _jsxs("div", { className: "flex flex-row items-center gap-2", children: [_jsx(Avatar, { src: "/cloud.svg", name: "SA", color: "bg-amber-500", className: "px-[5px] text-white", size: size }), showTitle && _jsxs("div", { className: "text-sm font-semibold pl-2 truncate", children: ["Service Account : ", accountId] })] }) }));
}
function ErrorAvatar({ title = "Error", error, showTitle = false, size = "md" }) {
    return (_jsx(UnknownAvatar, { title: title, message: typeof error === 'string' ? error : error.message, color: "bg-red-500", showTitle: showTitle, size: size }));
}
export function UserInfo({ userRef, showTitle = false, size = "md" }) {
    if (!userRef) {
        return _jsx(UnknownAvatar, { title: "Unknown User", message: "User information is not available.", showTitle: showTitle, size: size });
    }
    const [type, id] = userRef ? userRef.split(':') : ["unknown"];
    switch (type) {
        case PrincipalType.User:
            return _jsx(UserAvatar, { userId: id, showTitle: showTitle, size: size });
        case PrincipalType.Group:
            return _jsx(GroupAvatar, { userId: id, showTitle: showTitle, size: size });
        case "system":
            return _jsx(SystemAvatar, { showTitle: showTitle, size: size });
        case PrincipalType.ServiceAccount:
            return _jsx(ServiceAccountAvatar, { accountId: id, showTitle: showTitle, size: size });
        case PrincipalType.Agent:
            return _jsx(ServiceAccountAvatar, { accountId: id, showTitle: showTitle, size: size });
        case PrincipalType.ApiKey:
            return _jsx(ApiKeyAvatar, { keyId: id, size: size, showTitle: showTitle });
        default:
            return _jsx(ErrorAvatar, { title: "Unknown User", error: `Invalid user ref type: ${type}`, showTitle: showTitle, size: size });
    }
}
function UnknownAvatar({ title, message, color, size = "md", showTitle = false }) {
    return (_jsx(UserPopoverPanel, { title: title, description: message, children: _jsxs("div", { className: "flex flex-row items-center gap-2", children: [_jsx(Avatar, { color: color, size: size }), showTitle && _jsx("div", { className: "text-sm font-semibold pl-1", children: title })] }) }));
}
function GroupAvatar({ userId, showTitle = false, size = "md" }) {
    const { data: group, error } = useFetchGroupInfo(userId);
    if (error) {
        return _jsx(ErrorAvatar, { title: "Failed to fetch group", error: error, showTitle: showTitle, size: size });
    }
    if (!group) {
        return _jsx(AvatarPlaceholder, {});
    }
    const description = (_jsxs("div", { className: "space-y-1", children: [group.description && _jsx("div", { className: "text-sm", children: group.description }), _jsxs("div", { className: "text-xs text-muted-foreground", children: ["Group ID: ", group.id] }), group.tags && group.tags.length > 0 && (_jsx("div", { className: "flex flex-wrap gap-1", children: group.tags.map(tag => (_jsx("span", { className: "px-1.5 py-0.5 bg-muted rounded text-xs", children: tag }, tag))) }))] }));
    return (_jsx(UserPopoverPanel, { title: group.name || "Unnamed Group", description: description, children: _jsxs("div", { className: "flex flex-row items-center gap-2", children: [_jsx(Users, { className: "size-6 text-indigo-500", size: size }), showTitle && _jsx("div", { className: "text-sm font-semibold pl-2", children: group.name || "Unnamed Group" })] }) }));
}
function UserAvatar({ userId, showTitle = false, size = "md" }) {
    const { data: user, error } = useFetchUserInfo(userId);
    if (error) {
        return _jsx(ErrorAvatar, { title: "Failed to fetch user", error: error, showTitle: showTitle, size: size });
    }
    if (!user) {
        return _jsx(AvatarPlaceholder, {});
    }
    const description = (_jsx("div", { className: "truncate", title: user.email, children: user.email }));
    return (_jsx(UserPopoverPanel, { title: user.name || user.email || user.username || "unknown", description: description, children: _jsxs("div", { className: "flex flex-row items-center gap-2", children: [_jsx(Avatar, { src: user.picture, name: user.name, color: "bg-indigo-500", size: size }), showTitle && _jsx("div", { className: "text-sm font-semibold pl-2", children: user.name || user.email || user.username || "unknown" })] }) }));
}
export function ApiKeyAvatar({ keyId, showTitle = false, size = "md" }) {
    const { client } = useUserSession();
    const { data, error } = useFetch(() => client.apikeys.retrieve(keyId), []);
    if (error) {
        return _jsx(ErrorAvatar, { title: "Failed to fetch the apikey", error: error, showTitle: showTitle, size: size });
    }
    if (!data) {
        return _jsx(AvatarPlaceholder, {});
    }
    const title = "Private Key";
    const avatar = _jsx(Avatar, { name: "PK", color: "bg-pink-500", size: size });
    const description = (_jsxs(Table, { className: "dark:bg-gray-800 dark:text-gray-200 table-fixed w-full", children: [_jsxs("tr", { children: [_jsx("td", { className: "font-semibold w-20", children: "Key:" }), _jsx("td", { className: "truncate max-w-0", children: data?.name })] }), _jsxs("tr", { children: [_jsx("td", { className: "font-semibold w-20", children: "Account:" }), _jsx("td", { className: "truncate max-w-0", children: data?.account })] }), _jsxs("tr", { children: [_jsx("td", { className: "font-semibold w-20", children: "Project:" }), _jsx("td", { className: "truncate max-w-0", children: data?.project.name })] })] }));
    return (_jsx(UserPopoverPanel, { title: title, description: description, children: _jsxs("div", { className: "flex flex-row items-center gap-2", children: [avatar, showTitle && _jsx("div", { className: "text-sm font-semibold", children: data?.name || data?.account || data?.project.name || "unknown" })] }) }));
}
function UserPopoverPanel({ title, description, children }) {
    return (_jsxs(Popover, { hover: true, children: [_jsx(PopoverTrigger, { className: "cursor-pointer flex items-center inline-block", children: _jsx("div", { children: children }) }), _jsx(PopoverContent, { align: "center", sideOffset: 8, side: "right", children: _jsxs("div", { className: "flex flex-col gap-1 rounded-md shadow-md p-2", children: [_jsx("div", { className: 'text-md font-semibold', children: title }), description] }) })] }));
}
//# sourceMappingURL=UserInfo.js.map