{% extends "_layouts/cp" %}

{% set selectedSubnavItem = 'tokens' %}

{% set fullPageForm = true %}

{% set crumbs = [
    { label: "GraphQL Tokens"|t('app'), url: url('graphql/tokens') }
] %}

{% import "_includes/forms" as forms %}

{% block content %}
    <input type="hidden" name="action" value="graphql/save-token">
    {{ redirectInput('graphql/tokens') }}
    {% if token.id %}<input type="hidden" name="tokenId" value="{{ token.id }}">{% endif %}

    {{ forms.textField({
        first: true,
        label: "Name"|t('app'),
        instructions: "What this token will be called in the control panel."|t('app'),
        id: 'name',
        name: 'name',
        value: token.name,
        errors: token.getErrors('name'),
        autofocus: true,
        required: true,
    }) }}

    {% set schemaInput = schemaOptions
        ? forms.selectField({
            name: 'schema',
            id: 'schema',
            options: schemaOptions,
            value: token.schemaId,
        })
        : tag('p', {
            class: ['warning', 'with-icon'],
            text: 'No schemas exist yet to assign to this token.'|t('app'),
        })
    %}

    {{ forms.field({
        id: 'schema',
        label: 'GraphQL Schema',
        instructions: 'Choose which GraphQL schema this token has access to.',
    }, schemaInput) }}

    <hr>

    {% embed '_includes/forms/field' with {
        label: 'Authorization Header'|t('app'),
        instructions: 'The `Authorization` header that should be sent with GraphQL API requests to use this token.'|t('app'),
        id: 'auth-header',
    } %}
        {% block input %}
            {% import '_includes/forms' as forms %}
            <div class="flex">
                {% embed '_includes/forms/copytext' with {
                    id: 'auth-header',
                    buttonId: 'copy-btn',
                    value: 'Authorization: Bearer ' ~ (accessToken ?? '••••••••••••••••••••••••••••••••'),
                    errors: token.getErrors('accessToken'),
                    class: ['code', not accessToken ? 'disabled']|filter,
                    size: 54,
                } %}
                    {# don't register the default JS #}
                    {% block js %}{% endblock %}
                {% endembed %}
                {{ hiddenInput('accessToken', accessToken, {
                    id: 'access-token',
                    disabled: not accessToken,
                }) }}
                <button type="button" id="regen-btn" class="btn">{{ 'Regenerate'|t('app') }}</button>
                <div id="token-spinner" class="spinner hidden"></div>
            </div>
        {% endblock %}
    {% endembed %}
{% endblock %}

{% block details %}
    <div class="meta">
        {{ forms.lightswitchField({
            label: 'Enabled'|t('app'),
            id: 'enabled',
            name: 'enabled',
            on: token.enabled,
        }) }}

        {{ forms.dateTimeField({
            label: "Expiry Date"|t('app'),
            id: 'expiryDate',
            name: 'expiryDate',
            value: (token.expiryDate ? token.expiryDate : null),
            errors: token.getErrors('expiryDate')
        }) }}
    </div>
{% endblock %}

{% js %}
    var $headerInput = $('#auth-header');
    var $tokenInput = $('#access-token');
    var $regenBtn = $('#regen-btn');
    var regenerating = false;

    function copyHeader() {
        $headerInput[0].select();
        document.execCommand('copy');
        Craft.cp.displayNotice("{{ 'Copied to clipboard.'|t('app')|e('js') }}");
    }

    $headerInput.on('click', function() {
        if (!$headerInput.hasClass('disabled')) {
            this.select();
        }
    });

    $('#copy-btn').on('click', function() {
        if (!$headerInput.hasClass('disabled')) {
            copyHeader();
        } else {
            Craft.elevatedSessionManager.requireElevatedSession(function() {
            $('#token-spinner').removeClass('hidden');
            var data = {{ {tokenUid: token.uid}|json_encode|raw }};
            Craft.sendActionRequest('POST', 'graphql/fetch-token', {data})
                .then((response) => {
                    $('#token-spinner').addClass('hidden');
                    $headerInput
                        .val('Authorization: Bearer ' + response.data.accessToken)
                        .removeClass('disabled');
                    copyHeader();
                })
                .finally(() => {
                    $('#token-spinner').addClass('hidden');
                });
            });
        }
    });

    $regenBtn.on('click', function() {
        if (regenerating) {
            return;
        }
        regenerating = true;
        $('#token-spinner').removeClass('hidden');
        $regenBtn.addClass('active');

        Craft.sendActionRequest('POST', 'graphql/generate-token')
            .then((response) => {
                $headerInput
                    .val('Authorization: Bearer ' + response.data.accessToken)
                    .removeClass('disabled');
                $tokenInput
                    .val(response.data.accessToken)
                    .prop('disabled', false);
                $regenBtn.removeClass('active');
                regenerating = false;
            })
            .finally(() => {
                $('#token-spinner').addClass('hidden');
            });
        });

    new Craft.ElevatedSessionForm('#main-form');
{% endjs %}
