import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
/*
 * Copyright (c) 2023-2025 Datalayer, Inc.
 * Distributed under the terms of the Modified BSD License.
 */
import { useState, useEffect, useRef } from 'react';
import { PageLayout, Button, IconButton, Text, Label, RelativeTime, ConfirmationDialog, } from '@primer/react';
import { Blankslate, PageHeader, Table, DataTable, } from '@primer/react/experimental';
import { Box } from '@datalayer/primer-addons';
import { EditIcon } from '@datalayer/icons-react';
import { TrashIcon } from '@primer/octicons-react';
import { useCache, useNavigate, useToast } from '../../hooks/index.js';
const TokensTable = ({ tokensListRoute, showTitle = true, }) => {
    const { useTokens, useDeleteToken } = useCache();
    const { enqueueToast } = useToast();
    const getTokensQuery = useTokens();
    const deleteTokenMutation = useDeleteToken();
    const navigate = useNavigate();
    const [tokens, setTokens] = useState([]);
    const [deletingToken, setDeletingToken] = useState(null);
    const returnFocusRef = useRef(null);
    useEffect(() => {
        if (getTokensQuery.data) {
            setTokens(getTokensQuery.data);
        }
    }, [getTokensQuery.data]);
    const handleDeleteConfirm = () => {
        if (!deletingToken)
            return;
        deleteTokenMutation.mutate(deletingToken.id, {
            onSuccess: (resp) => {
                if (resp.success) {
                    enqueueToast(`Token "${deletingToken.name}" deleted.`, {
                        variant: 'success',
                    });
                }
                else {
                    enqueueToast(resp.message || 'Failed to delete token.', {
                        variant: 'error',
                    });
                }
            },
            onError: () => {
                enqueueToast('Failed to delete token.', { variant: 'error' });
            },
            onSettled: () => setDeletingToken(null),
        });
    };
    return tokens.length === 0 ? (_jsxs(Blankslate, { border: true, spacious: true, children: [showTitle && _jsx(Blankslate.Heading, { children: "API Keys" }), _jsx(Blankslate.Description, { children: _jsx(Text, { sx: { textAlign: 'center' }, children: "No API Keys found." }) })] })) : (_jsxs(_Fragment, { children: [_jsxs(Table.Container, { children: [showTitle && (_jsxs(_Fragment, { children: [_jsx(Table.Title, { as: "h2", id: "tokens", children: "API Keys" }), _jsx(Table.Subtitle, { as: "p", id: "tokens-subtitle", children: "Your tokens." })] })), _jsx(DataTable, { "aria-labelledby": "teams", "aria-describedby": "teams-subtitle", data: tokens, columns: [
                            {
                                header: 'Type',
                                field: 'variant',
                                renderCell: token => _jsx(Label, { children: token.variant }),
                            },
                            {
                                header: 'Name',
                                field: 'name',
                                rowHeader: true,
                            },
                            {
                                header: 'Description',
                                field: 'description',
                            },
                            {
                                header: 'Expiration date',
                                field: 'expirationDate',
                                renderCell: token => (_jsx(RelativeTime, { date: new Date(token.expirationDate) })),
                            },
                            {
                                header: '',
                                field: 'id',
                                renderCell: token => (_jsxs(Box, { display: "flex", sx: { gap: 1 }, children: [_jsx(IconButton, { icon: EditIcon, "aria-label": "Edit", size: "small", variant: "invisible", onClick: e => navigate(tokensListRoute
                                                ? `${tokensListRoute}/${token.id}`
                                                : `${token.id}`, e) }), _jsx(IconButton, { ref: returnFocusRef, icon: TrashIcon, "aria-label": "Delete", size: "small", variant: "invisible", sx: { color: 'danger.fg' }, onClick: () => setDeletingToken(token) })] })),
                            },
                        ] })] }), deletingToken && (_jsxs(ConfirmationDialog, { title: "Delete token", onClose: gesture => {
                    if (gesture === 'confirm')
                        handleDeleteConfirm();
                    else
                        setDeletingToken(null);
                }, confirmButtonContent: "Delete", confirmButtonType: "danger", children: ["Are you sure you want to delete the token", ' ', _jsx("strong", { children: deletingToken.name }), "? This action cannot be undone."] }))] }));
};
export const IAMTokens = ({ newTokenRoute = '/new/token', tokensListRoute, showTitle = true, } = {}) => {
    const navigate = useNavigate();
    return (_jsxs(PageLayout, { containerWidth: "full", padding: "normal", style: { overflow: 'visible', minHeight: 'calc(100vh - 45px)' }, children: [_jsx(PageLayout.Header, { children: _jsxs(PageHeader, { children: [showTitle && (_jsx(PageHeader.TitleArea, { variant: "large", children: _jsx(PageHeader.Title, { children: "API Keys" }) })), _jsx(PageHeader.Actions, { children: _jsx(Button, { size: "small", variant: "primary", onClick: e => navigate(newTokenRoute, e), children: "New API Key" }) })] }) }), _jsx(PageLayout.Content, { children: _jsx(Box, { children: _jsx(TokensTable, { tokensListRoute: tokensListRoute, showTitle: showTitle }) }) })] }));
};
export default IAMTokens;
