// ==================== Admin Panel Functions ====================

async function loadSettings() {
    try {
        const response = await fetch('/api/admin/settings');

        if (response.status === 401) {
            window.location.href = '/login';
            return;
        }

        if (response.status === 403) {
            showMessage('Admin access required', 'error');
            return;
        }

        const data = await response.json();

        // Update checkbox state
        document.getElementById('allow-registration').checked =
            data.allow_registration === 'true' || data.allow_registration === true;

    } catch (error) {
        console.error('Error loading settings:', error);
        showMessage('Error loading settings: ' + error.message, 'error');
    }
}

async function toggleRegistration(checkbox) {
    try {
        const formData = new FormData();
        formData.append('value', checkbox.checked ? 'true' : 'false');

        const response = await fetch('/api/admin/settings/allow_registration', {
            method: 'PUT',
            body: formData
        });

        if (response.status === 401) {
            window.location.href = '/login';
            return;
        }

        if (response.status === 403) {
            showMessage('Admin access required', 'error');
            return;
        }

        const data = await response.json();

        if (data.status === 'success') {
            showMessage(
                checkbox.checked ? 'Registration enabled' : 'Registration disabled',
                'success'
            );
        } else {
            showMessage(data.message || 'Failed to update setting', 'error');
            // Revert checkbox
            checkbox.checked = !checkbox.checked;
        }
    } catch (error) {
        showMessage('Error updating setting: ' + error.message, 'error');
        // Revert checkbox
        checkbox.checked = !checkbox.checked;
    }
}

async function loadUsers() {
    try {
        const loadingEl = document.getElementById('users-loading');
        const containerEl = document.getElementById('users-container');

        loadingEl.classList.remove('hidden');
        containerEl.classList.add('hidden');

        const response = await fetch('/api/admin/users');

        if (response.status === 401) {
            window.location.href = '/login';
            return;
        }

        if (response.status === 403) {
            showMessage('Admin access required', 'error');
            return;
        }

        const data = await response.json();

        loadingEl.classList.add('hidden');
        containerEl.classList.remove('hidden');

        renderUsers(data.users || []);

    } catch (error) {
        console.error('Error loading users:', error);
        showMessage('Error loading users: ' + error.message, 'error');
        document.getElementById('users-loading').classList.add('hidden');
    }
}

function renderUsers(users) {
    const listEl = document.getElementById('users-list');

    if (users.length === 0) {
        listEl.innerHTML = '<tr><td colspan="8" style="text-align: center;">No users found</td></tr>';
        return;
    }

    const html = users.map(user => {
        const createdDate = new Date(user.created_at).toLocaleDateString();
        const lastLogin = user.last_login ? new Date(user.last_login).toLocaleDateString() : 'Never';

        return `
            <tr>
                <td>${user.username}</td>
                <td>${user.email}</td>
                <td>${user.display_name || '-'}</td>
                <td>${user.is_admin ? '<span class="badge badge-admin">Admin</span>' : '-'}</td>
                <td>${user.is_active ? '<span class="badge badge-active">Active</span>' : '<span class="badge badge-inactive">Inactive</span>'}</td>
                <td>${createdDate}</td>
                <td>${lastLogin}</td>
                <td>
                    ${!user.is_admin ? `
                        <button class="btn btn-small btn-secondary" onclick="toggleAdmin(${user.id}, true)">Make Admin</button>
                    ` : ''}
                    ${!user.is_current ? `
                        <button class="btn btn-small btn-danger" onclick="deleteUser(${user.id}, '${user.username}')">Delete</button>
                    ` : '<span class="text-muted">Current User</span>'}
                </td>
            </tr>
        `;
    }).join('');

    listEl.innerHTML = html;
}

async function toggleAdmin(userId, makeAdmin) {
    if (!confirm(`Are you sure you want to ${makeAdmin ? 'grant' : 'remove'} admin privileges ${makeAdmin ? 'to' : 'from'} this user?`)) {
        return;
    }

    try {
        const formData = new FormData();
        formData.append('is_admin', makeAdmin ? 'true' : 'false');

        const response = await fetch(`/api/admin/users/${userId}/admin`, {
            method: 'PUT',
            body: formData
        });

        if (response.status === 401) {
            window.location.href = '/login';
            return;
        }

        const data = await response.json();

        if (data.status === 'success') {
            showMessage('User privileges updated successfully', 'success');
            loadUsers(); // Reload user list
        } else {
            showMessage(data.message || 'Failed to update user', 'error');
        }
    } catch (error) {
        showMessage('Error updating user: ' + error.message, 'error');
    }
}

async function deleteUser(userId, username) {
    if (!confirm(`Are you sure you want to delete user "${username}"? This action cannot be undone and will delete all their data.`)) {
        return;
    }

    try {
        const response = await fetch(`/api/admin/users/${userId}`, {
            method: 'DELETE'
        });

        if (response.status === 401) {
            window.location.href = '/login';
            return;
        }

        const data = await response.json();

        if (data.status === 'success') {
            showMessage('User deleted successfully', 'success');
            loadUsers(); // Reload user list
        } else {
            showMessage(data.message || 'Failed to delete user', 'error');
        }
    } catch (error) {
        showMessage('Error deleting user: ' + error.message, 'error');
    }
}
