document.addEventListener("DOMContentLoaded", function () {
    const currentPasswordInput = document.getElementById("currentPasswordInput");
    const oldPasswordMatchError = document.getElementById("oldPasswordMatchError");
    const passwordForm = document.getElementById("settingsContainer");
    const passwordInput1 = document.querySelector('input[name="new_password"]');
    const passwordInput2 = document.querySelector('input[name="confirm_password"]');
    const passwordMatchError = document.getElementById('passwordMatchError');


    passwordForm.addEventListener("submit", function (e) {
        e.preventDefault(); // Prevent the default form submission.

        // Clear error messages.
        oldPasswordMatchError.textContent = '';
        passwordMatchError.textContent = '';

        // Get the entered passwords.
        const currentPassword = currentPasswordInput.value;
        const newPassword1 = passwordInput1.value;
        const newPassword2 = passwordInput2.value;

        // Function to get the CSRF token from cookies.
        function getCookie(name) {
            var cookieValue = null;
            if (document.cookie && document.cookie !== '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = cookies[i].trim();
                    if (cookie.substring(0, name.length + 1) === (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }

        // Function to check passwords and perform validation
        function validatePasswords() {
            // Password strength requirements
            const isLengthValid = newPassword1.length >= 8;

            if (newPassword1 && newPassword2) {
                if (newPassword1 === newPassword2) {
                    let errorMessage = '';

                    if (!isLengthValid) {
                        errorMessage += '- At least 8 characters\n';
                    }

                    if (errorMessage) {
                        passwordMatchError.textContent = errorMessage;
                        passwordMatchError.style.whiteSpace = 'pre-line';
                    }
                } else {
                    passwordMatchError.textContent = 'Passwords do not match';
                }
            }
        }

        // Check if the passwords match and perform validation
        if (currentPassword && newPassword1 && newPassword2) {
            // Send an AJAX request to check the current password.
            fetch('/check_current_password/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': getCookie('csrftoken')
                },
                body: JSON.stringify({ current_password: currentPassword }),
            })
                .then(response => response.json())
                .then(data => {
                    if (data.is_current_password_correct) {
                        // Current password is correct, now validate the new passwords.
                        validatePasswords();
                        
                        // Check if there are any error messages.
                        if (!oldPasswordMatchError.textContent && !passwordMatchError.textContent) {
                            // Password checks passed, submit the form.
                            passwordForm.submit();
                        }
                    } else {
                        // Password is incorrect. Display an error message.
                        oldPasswordMatchError.textContent = 'Incorrect password';
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                });
        }
    });
});
