<div
    x-data="{
        current_permission: '{{ perm_data.level_verbose }}',
        permission_choices: ['None', 'View', 'Add', 'Change', 'Delete'],
        loading: false,
        error_message: '',
        show_dropdown: false,

        async update(perm) {
            this.show_dropdown = false
            this.error_message = null

            if(this.current_permission !== perm) {
                this.loading = true
                let response = await ajax_request(
                    'POST',
                    '{% url "django_spire:auth:group:json:group_permission_ajax" app_name=perm_data.app_name pk=group.pk %}',
                    {'perm_level': perm}
                )
                this.loading = false
                let status = response.data.status
                if (status === 200){
                    this.current_permission = perm
                } else {
                    this.error_message = response.data.message
                }
            }
        }
    }"
>
    <div class="position-relative">
        <div @click="show_dropdown = true" class="btn btn-sm border dropdown-toggle">
            <span x-text="current_permission"></span>
        </div>
        <div
            style="width: 80px; z-index: 2"
            class="card position-absolute bg-app-layer-one mt-1 border"
            x-show="show_dropdown"
            @click.outside="show_dropdown = false"
        >
            <template x-for="perm in permission_choices">
                <div
                    class="py-1 ps-2 cursor-pointer bg-app-layer-three-hover"
                    :class="{ 'border-bottom': perm !== 'Delete' }"
                    :style="
                        perm === 'None' ? 'border-top-left-radius: 0.30rem !important; border-top-right-radius: 0.30rem !important;' :
                        perm === 'Delete' ? 'border-bottom-left-radius: 0.30rem !important; border-bottom-right-radius: 0.30rem !important;' : ''
                    "
                    @click="update(perm)"
                >
                    <span
                        class="fs--1"
                        :class="{ 'text-app-secondary': perm === current_permission }"
                        x-text="perm"
                    ></span>
                </div>
            </template>
        </div>
    </div>
    <template x-if="error_message">
        <div x-text="error_message" class="fs--1 text-app-danger"></div>
    </template>
</div>
