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 { useEffect, useState } from 'react';
import { PageHeader, FormControl, Button, TextInput, Textarea, Select, Text, IconButton, } from '@primer/react';
import { Box } from '@datalayer/primer-addons';
import { CopyIcon } from '@primer/octicons-react';
import { Calendar, defaultCalendarStrings } from '@fluentui/react';
import { useCache, useNavigate, useToast } from '../../hooks/index.js';
import { useRunStore } from '../../state/index.js';
export const IAMTokenNew = ({ tokensListRoute = '/settings/iam/tokens', } = {}) => {
    const runStore = useRunStore();
    const { useCreateToken } = useCache();
    const createTokenMutation = useCreateToken();
    const navigate = useNavigate();
    const { enqueueToast } = useToast();
    const [today, _] = useState(new Date());
    const [showToken, setShowToken] = useState(false);
    const [token, setToken] = useState();
    const [formValues, setFormValues] = useState({
        variant: 'user_token',
        name: undefined,
        description: undefined,
        expirationDate: undefined,
    });
    const [validationResult, setValidationResult] = useState({
        variant: undefined,
        name: undefined,
        description: undefined,
        expirationDate: undefined,
    });
    const valueVariantChange = (event) => {
        setFormValues(prevFormValues => ({
            ...prevFormValues,
            variant: event.target.value,
        }));
    };
    const valueNameChange = (event) => {
        setFormValues(prevFormValues => ({
            ...prevFormValues,
            name: event.target.value,
        }));
    };
    const valueDescriptionChange = (event) => {
        setFormValues(prevFormValues => ({
            ...prevFormValues,
            description: event.target.value,
        }));
    };
    const expirationDateChange = (expirationDate) => {
        setFormValues(prevFormValues => ({
            ...prevFormValues,
            expirationDate,
        }));
    };
    useEffect(() => {
        setValidationResult({
            ...validationResult,
            name: formValues.name === undefined
                ? undefined
                : formValues.name.length > 2
                    ? true
                    : false,
            description: formValues.description === undefined
                ? undefined
                : formValues.description.length > 2
                    ? true
                    : false,
            expirationDate: formValues.expirationDate === undefined
                ? undefined
                : formValues.expirationDate.getTime() > today.getTime()
                    ? true
                    : false,
        });
    }, [formValues]);
    const valueSubmit = () => {
        runStore.layout().showBackdrop('Creating an token...');
        createTokenMutation.mutate({
            name: formValues.name,
            variant: formValues.variant,
            description: formValues.description,
            expirationDate: formValues.expirationDate,
        }, {
            onSuccess: (resp) => {
                if (resp.success && resp.token) {
                    enqueueToast(resp.message, { variant: 'success' });
                    setToken(resp.token);
                    setShowToken(true);
                }
            },
            onSettled: () => {
                runStore.layout().hideBackdrop();
            },
        });
    };
    return (_jsx(Box, { children: showToken ? (_jsxs(_Fragment, { children: [_jsx(PageHeader, { children: _jsx(PageHeader.TitleArea, { variant: "large", children: _jsx(PageHeader.Title, { children: "Your API Key is created" }) }) }), _jsx(Box, { children: _jsx(Text, { children: "Take note of the API Key value, you will not be able to see it after." }) }), _jsx(Box, { children: _jsxs(Text, { children: ["Name: ", token?.name] }) }), _jsx(Box, { children: _jsxs(Text, { children: ["Description: ", token?.description] }) }), _jsx(Box, { children: _jsxs(Text, { children: ["Expiration date: ", token?.expirationDate.toISOString()] }) }), _jsxs(Box, { children: [_jsx(Text, { mb: 2, children: "Value: " }), _jsxs(Box, { display: "flex", sx: { alignItems: 'center', gap: 2 }, children: [_jsx(Text, { as: "code", sx: {
                                        color: 'fg.onEmphasis',
                                        bg: 'neutral.emphasis',
                                        p: 2,
                                        overflowWrap: 'anywhere',
                                        flex: 1,
                                    }, children: token?.value }), _jsx(IconButton, { "aria-label": "Copy token to clipboard", icon: CopyIcon, size: "small", onClick: () => {
                                        if (token?.value) {
                                            navigator.clipboard.writeText(token.value);
                                            enqueueToast('Token copied to clipboard', {
                                                variant: 'success',
                                            });
                                        }
                                    } })] })] }), _jsx(Box, { mt: 3, children: _jsx(Button, { onClick: e => navigate(tokensListRoute, e), children: "List my API Keys" }) })] })) : (_jsxs(_Fragment, { children: [_jsx(PageHeader, { children: _jsx(PageHeader.TitleArea, { variant: "large", children: _jsx(PageHeader.Title, { children: "New API Key" }) }) }), _jsx(Box, { display: "grid", gridTemplateColumns: "1fr 1fr", sx: { gap: 3 }, children: _jsx(Box, { children: _jsxs(Box, { sx: { label: { marginTop: 2 } }, children: [_jsxs(FormControl, { required: true, children: [_jsx(FormControl.Label, { children: "Token type" }), _jsx(Select, { name: "type", value: formValues.variant, onChange: valueVariantChange, children: _jsx(Select.Option, { value: "user_token", children: "User Token" }) }), _jsx(FormControl.Caption, { children: "Pick the most appropriate token type." })] }), _jsxs(FormControl, { required: true, children: [_jsx(FormControl.Label, { children: "Name" }), _jsx(TextInput, { block: true, value: formValues.name, onChange: valueNameChange, autoFocus: true }), _jsx(FormControl.Caption, { children: "Hint: The token name is a short name that identifies in a unique way your token." }), validationResult.name === false && (_jsx(FormControl.Validation, { variant: "error", children: "Name length must be between 2 and 32 characters." }))] }), _jsxs(FormControl, { required: true, children: [_jsx(FormControl.Label, { children: "Expiration day" }), _jsx(Calendar, { showGoToToday: true, onSelectDate: expirationDateChange, value: formValues.expirationDate, strings: defaultCalendarStrings }), validationResult.expirationDate !== true ? (_jsx(FormControl.Validation, { variant: "error", children: "Pick an expiration date in the future." })) : (_jsxs(FormControl.Validation, { variant: "success", children: ["Expiration date:", ' ', formValues.expirationDate?.toLocaleDateString(), "."] }))] }), _jsxs(FormControl, { required: true, children: [_jsx(FormControl.Label, { children: "Description" }), _jsx(Textarea, { block: true, value: formValues.description, onChange: valueDescriptionChange }), validationResult.description === false && (_jsx(FormControl.Validation, { variant: "error", children: "Description must have more than 2 characters." }))] }), _jsx(Button, { variant: "primary", disabled: !validationResult.name ||
                                        !validationResult.description ||
                                        !validationResult.expirationDate, sx: { marginTop: 2 }, onClick: e => {
                                        e.preventDefault();
                                        valueSubmit();
                                    }, children: "Create a token" })] }) }) })] })) }));
};
export default IAMTokenNew;
