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 } from 'react';
import { useParams } from 'react-router-dom';
import { PageHeader, Heading, Text, Button, TextInput, FormControl, Textarea, Label, } from '@primer/react';
import { Box } from '@datalayer/primer-addons';
import { BoringAvatar } from '../../components/avatars/index.js';
import { useCache, useNavigate, useToast } from '../../hooks/index.js';
import { useRunStore } from '../../state/index.js';
export const IAMTokenEdit = ({ tokensListRoute = '/settings/iam/tokens', } = {}) => {
    const { tokenId } = useParams();
    const runStore = useRunStore();
    const navigate = useNavigate();
    const { enqueueToast } = useToast();
    const { useUpdateToken, useToken, useDeleteToken } = useCache();
    const getTokenQuery = useToken(tokenId);
    const updateTokenMutation = useUpdateToken();
    const deleteTokenMutation = useDeleteToken();
    const [token, setToken] = useState();
    const [formValues, setFormValues] = useState({
        name: token?.name,
        nameConfirm: '',
        description: token?.description,
    });
    const [validationResult, setValidationResult] = useState({
        name: undefined,
        nameConfirm: undefined,
        description: undefined,
    });
    useEffect(() => {
        if (getTokenQuery.data) {
            const token = getTokenQuery.data;
            setToken(token);
            setFormValues({ ...token, nameConfirm: '' });
        }
    }, [getTokenQuery.data]);
    const nameNameChange = (event) => {
        setFormValues(prevFormValues => ({
            ...prevFormValues,
            name: event.target.value,
        }));
    };
    const nameConfirmChange = (event) => {
        setFormValues(prevFormValues => ({
            ...prevFormValues,
            nameConfirm: event.target.value,
        }));
    };
    const nameDescriptionChange = (event) => {
        setFormValues(prevFormValues => ({
            ...prevFormValues,
            description: event.target.value,
        }));
    };
    useEffect(() => {
        setValidationResult({
            ...validationResult,
            name: formValues.name === undefined
                ? undefined
                : formValues.name.length > 2
                    ? true
                    : false,
            nameConfirm: formValues.nameConfirm === token?.name ? true : false,
            description: formValues.description === undefined
                ? undefined
                : formValues.description.length > 2
                    ? true
                    : false,
        });
    }, [formValues]);
    const nameSubmit = async () => {
        runStore.layout().showBackdrop();
        const updatedToken = {
            ...token,
            name: formValues.name,
            description: formValues.description,
        };
        updateTokenMutation.mutate(updatedToken, {
            onSuccess: (resp) => {
                if (resp.success) {
                    enqueueToast('The token is successfully updated.', {
                        variant: 'success',
                    });
                    setToken(updatedToken);
                }
            },
            onSettled: () => {
                runStore.layout().hideBackdrop();
            },
        });
    };
    const handleDelete = async () => {
        runStore.layout().showBackdrop('Deleting the token...');
        deleteTokenMutation.mutate(token.id, {
            onSuccess: (resp) => {
                if (resp.success) {
                    enqueueToast('The token is successfully deleted.', {
                        variant: 'success',
                    });
                    navigate(tokensListRoute);
                }
                else {
                    enqueueToast(resp.message || 'Failed to delete token.', {
                        variant: 'error',
                    });
                }
            },
            onError: () => {
                enqueueToast('Failed to delete token.', { variant: 'error' });
            },
            onSettled: () => {
                runStore.layout().hideBackdrop();
            },
        });
    };
    return (_jsxs(_Fragment, { children: [_jsx(PageHeader, { children: _jsx(Heading, { sx: { fontSize: 3 }, children: "API Key" }) }), _jsxs(Box, { display: "flex", children: [_jsxs(Box, { children: [_jsx(BoringAvatar, { displayName: token?.name, size: 100, style: { paddingRight: 10 } }), _jsx(Text, { as: "h2", sx: { paddingTop: 3 }, children: token?.name }), _jsx(Box, { mt: 3, children: _jsx(Label, { size: "large", children: token?.variant }) })] }), _jsxs(Box, { ml: 10, children: [_jsxs(Box, { sx: { label: { marginTop: 2 } }, children: [_jsxs(FormControl, { children: [_jsx(FormControl.Label, { children: "Name" }), _jsx(TextInput, { block: true, value: formValues.name, onChange: nameNameChange }), validationResult.name === false && (_jsx(FormControl.Validation, { variant: "error", children: "Name must have more than 2 characters." }))] }), _jsxs(FormControl, { children: [_jsx(FormControl.Label, { children: "Description" }), _jsx(Textarea, { block: true, value: formValues.description, onChange: nameDescriptionChange, rows: 5 }), validationResult.description === false && (_jsx(FormControl.Validation, { variant: "error", children: "Description must have more than 2 characters." }))] }), _jsxs(FormControl, { children: [_jsx(FormControl.Label, { children: "Expiration date" }), _jsx(TextInput, { block: true, value: token?.expirationDate.toLocaleDateString(), onChange: nameNameChange, disabled: true })] }), _jsx(Button, { variant: "primary", disabled: !validationResult.name || !validationResult.description, sx: { marginTop: 3 }, onClick: nameSubmit, children: "Update token" })] }), _jsxs(Box, { sx: { marginTop: 3 }, children: [_jsx(Heading, { as: "h2", sx: {
                                            fontSize: 4,
                                            fontWeight: 'normal',
                                            color: 'danger.fg',
                                            mb: 2,
                                        }, children: "Danger zone" }), _jsxs(Box, { sx: {
                                            border: '1px solid',
                                            borderColor: 'danger.emphasis',
                                            borderRadius: 2,
                                            p: 3,
                                            display: 'flex',
                                            alignItems: 'center',
                                            justifyContent: 'space-between',
                                            gap: 3,
                                        }, children: [_jsxs(Box, { sx: { display: 'grid', gap: 1 }, children: [_jsx(Text, { sx: { fontSize: 1, fontWeight: 'bold', color: 'danger.fg' }, children: "Confirm the token name to delete" }), _jsx(FormControl, { children: _jsx(TextInput, { block: true, value: formValues.nameConfirm, onChange: nameConfirmChange }) }), _jsx(Text, { sx: { fontSize: 1, color: 'fg.muted' }, children: "This operation is not reversible." })] }), _jsx(Button, { variant: "danger", disabled: !validationResult.nameConfirm, onClick: handleDelete, children: "Delete token" })] })] })] })] })] }));
};
export default IAMTokenEdit;
