const loginError = document.getElementById('auth-error');

$(document).ready(function () {
    $('#save_changes').click(function () {
        let username = $('#username').text();
        let email = $('#email').text();
        let password = $('#password').text();
        let is_active = $('#edit_active').is(':checked');
        let is_verified = $('#edit_verified').is(':checked');
        let is_superuser = $('#edit_superuser').is(':checked');
        let user_guid = $('#user_guid')[0].value;

        let request_body = {
            "username": username,
            "email": email,
            "password": password,
            "is_active": is_active,
            "is_verified": is_verified,
            "is_superuser": is_superuser
        };

        $.ajax({
            url: '/manage/' + user_guid,
            type: 'PUT',
            contentType: 'application/json',
            data: JSON.stringify(request_body),
            success: function (result) {
                let toast = document.getElementById("error-msg");
                if (!toast) {
                    toast = document.createElement('div');
                    toast.id = "success-msg";
                    toast.classList.add("toast", "toast-success");
                    loginError.appendChild(toast);
                }
                toast.innerText = "User updated successfully.";
            },
            error: function (xhr, textStatus, errorThrown) {
                let errorMessage = xhr.responseJSON.detail;
                let toast = document.getElementById("error-msg");
                if (!toast) {
                    toast = document.createElement('div');
                    toast.id = "error-msg";
                    toast.classList.add("toast", "toast-error");
                    loginError.appendChild(toast);
                }
                toast.innerText = errorMessage;
            }
        });
    });
});
