const baseURL = '/api/v1/api/account/';

// ---------------------Register page validation start------------------

// Username validation function
function validateUsername(username) {
    const errors = [];
    if (!/^[a-zA-Z]/.test(username)) {
        errors.push('Username must start with a letter');
    }
    if (!/^[a-zA-Z0-9_-]+$/.test(username)) {
        errors.push('Username can only have A-Z, a-z, 0-9, _ , -');
    }
    if (/\s/.test(username)) {
        errors.push('Username cannot contain spaces');
    }
    if (username.length < 5 || username.length > 15) {
        errors.push('Username must contain 5 to 15 characters');
    }
    return errors;
}

document.getElementById('username').addEventListener('input', function () {
    const username = this.value.trim();
    clearError('usernameError');
    const usernameErrors = validateUsername(username);
    if (usernameErrors.length > 0) {
        showError('usernameError', usernameErrors[0]);
    } else {
        clearError('usernameError');
    }
});

// Function to toggle password visibility
$(".toggle-password, .toggle-confirmPassword").click(function() {
    $(this).toggleClass("fa-eye fa-eye-slash");
    let input = $(this).parent().find("input");
    input.attr("type", input.attr("type") === "password" ? "text" : "password");
});


// Password validation function
function validatePassword(password) {
    const errors = [];
    if (!/[A-Z]/.test(password)) {
        errors.push('At least 1 uppercase letter [A-Z]');
    }
    if (!/[a-z]/.test(password)) {
        errors.push('At least 1 lowercase letter [a-z]');
    }
    if (!/[0-9]/.test(password)) {
        errors.push('At least 1 numeric value [0-9]');
    }
    if (!/[!@#$%^&*(),.?":{}|<>]/.test(password)) {
        errors.push('At least 1 special character [!@#$%^&*(),.?":{}|<>]');
    }
    if (password.length < 6 || password.length > 12) {
        errors.push('Password must contain 6 to 12 characters');
    }
    return errors;
}

document.getElementById('password').addEventListener('input', function () {
    const password = this.value.trim();
    clearError('passwordError');
    const passwordErrors = validatePassword(password);
    if (passwordErrors.length > 0) {
        showError('passwordError', passwordErrors[0]);
    } else {
        clearError('passwordError');
    }
});

document.getElementById('confirmPassword').addEventListener('input', function () {
    const password = document.getElementById('password').value.trim();
    const confirmPassword = this.value.trim();
    clearError('confirmPasswordError');
    if (password !== confirmPassword) {
        showError('confirmPasswordError', 'Passwords do not match');
    } else {
        clearError('confirmPasswordError');
    }
});

function showError(elementId, message) {
    const errorElement = document.getElementById(elementId);
    errorElement.textContent = message;
    errorElement.style.display = 'block';
}

function clearError(elementId) {
    const errorElement = document.getElementById(elementId);
    errorElement.textContent = '';
    errorElement.style.display = 'none';
}

// Function to register a user (POST request)
async function registerUser(userData) {
    fetch(baseURL, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(userData)
    })
    .then(response => response.json())
    .then(data => {
        console.log('Success:', data);
        alert('Registration successful! Redirecting to login.');
        window.location.href = 'login.html';
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Registration failed. Please try again.');
    });
}

document.getElementById('createAccount').addEventListener('click', async function (event) {
    event.preventDefault();
    const username = document.getElementById('username').value.trim();
    const password = document.getElementById('password').value.trim();
    const confirmPassword = document.getElementById('confirmPassword').value.trim();

    if (!validateUsername(username).length && !validatePassword(password).length && password === confirmPassword) {
        await registerUser({ username, password });
    }
});

// Function to fetch all users (GET request)
async function fetchUsers() {
    try {
        const response = await fetch(baseURL, {
            method: 'GET',
            headers: { 'Content-Type': 'application/json' }
        });
        if (!response.ok) throw new Error('Failed to fetch users');
        return await response.json();
    } catch (error) {
        console.error('Error fetching users:', error);
        return [];
    }
}

// Function to update a user (PUT request)
async function registerUser(userData) {
    try {
        const users = await fetchUsers();
        const userExists = users.some(user => user.username === userData.username);

        if (userExists) {
            alert('User already exists! Please use a different username.');
            return;
        }

        const response = await fetch(baseURL, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(userData)
        });

        const data = await response.json();

        if (response.ok) {
            console.log('Success:', data);
            alert('Registration successful! Redirecting to login.');
            window.location.href = 'login.html';
        } else {
            throw new Error(data.message || 'Registration failed.');
        }
    } catch (error) {
        console.error('Error:', error);
        alert('Registration failed. Please try again.');
    }
}

// Function to delete a user (DELETE request)
async function deleteUser(userId) {
    fetch(`${baseURL}${userId}/`, {
        method: 'DELETE',
        headers: {
            'Content-Type': 'application/json'
        }
    })
    .then(response => {
        if (response.ok) {
            console.log('User deleted successfully');
            alert('User deleted successfully!');
        } else {
            throw new Error('Deletion failed');
        }
    })
    .catch(error => {
        console.error('Deletion failed:', error);
        alert('Failed to delete user. Please try again.');
    });
}
