let allUsers = [];

document.addEventListener('DOMContentLoaded', async () => {
    // Auth check is handled by main.js, but double check role
    const userRole = localStorage.getItem('role') || 'Manager'; // Assuming we store role
    // Wait, main.js auth check needs to be robust first. 
    // We will update main.js next.
    // For now, assume if we are here, we are admin (or will be kicked out)

    await loadUsers();
});

async function loadUsers() {
    try {
        allUsers = await app.apiGet('/users');
        displayUsers(allUsers);
    } catch (error) {
        console.error('Error loading users:', error);
        document.getElementById('usersTableBody').innerHTML = '<tr><td colspan="6" class="loading">Failed to load users</td></tr>';
    }
}

function displayUsers(users) {
    const tbody = document.getElementById('usersTableBody');
    if (users.length === 0) {
        tbody.innerHTML = '<tr><td colspan="6" class="loading">No users found</td></tr>';
        return;
    }

    tbody.innerHTML = users.map(user => {
        let permissionsDisplay = '';
        try {
            const perms = JSON.parse(user.permissions);
            if (perms.includes('*')) {
                permissionsDisplay = '<span class="badge badge-primary">Full Access</span>';
            } else {
                permissionsDisplay = `<span class="text-muted" style="font-size: 0.85rem;">${perms.length} Pages</span>`;
            }
        } catch (e) {
            permissionsDisplay = '-';
        }

        const statusClass = user.status === 'Active' ? 'active' : 'disabled';

        return `
        <tr>
            <td><strong>${user.username}</strong></td>
            <td>${user.role}</td>
            <td>${permissionsDisplay}</td>
            <td><span class="badge ${user.status === 'Active' ? 'badge-primary' : 'badge-danger'}">${user.status || 'Active'}</span></td>
            <td>${app.formatDate(user.created_at)}</td>
            <td>
                <button class="btn btn-secondary" onclick="openEditUserModal(${user.id})" style="padding: 0.25rem 0.5rem; font-size: 0.75rem;">Edit</button>
                ${user.username !== 'admin' && user.username !== localStorage.getItem('user') ?
                `<button class="btn btn-danger" onclick="deleteUser(${user.id})" style="padding: 0.25rem 0.5rem; font-size: 0.75rem; margin-left: 0.5rem;">Delete</button>` : ''}
            </td>
        </tr>
    `}).join('');
}

function openAddUserModal() {
    document.getElementById('modalTitle').textContent = 'Add User';
    document.getElementById('userForm').reset();
    document.getElementById('editUserId').value = '';
    document.getElementById('password').required = true;
    document.getElementById('passwordHint').style.display = 'none';
    document.getElementById('statusGroup').style.display = 'none';

    // Reset permissions
    document.querySelectorAll('input[name="permissions"]').forEach(cb => cb.checked = false);

    togglePermissions(); // Update visibility based on role (default Manager)
    document.getElementById('userModal').classList.add('active');
}

function openEditUserModal(userId) {
    const user = allUsers.find(u => u.id === userId);
    if (!user) return;

    document.getElementById('modalTitle').textContent = 'Edit User';
    document.getElementById('editUserId').value = user.id;
    document.getElementById('username').value = user.username;

    // Password optional on edit
    document.getElementById('password').value = '';
    document.getElementById('password').required = false;
    document.getElementById('passwordHint').style.display = 'inline';

    document.getElementById('role').value = user.role;

    // Status
    document.getElementById('statusGroup').style.display = 'block';
    document.getElementById('status').value = user.status || 'Active';

    // Permissions
    try {
        const perms = JSON.parse(user.permissions);
        document.querySelectorAll('input[name="permissions"]').forEach(cb => {
            cb.checked = perms.includes('*') || perms.includes(cb.value);
        });
    } catch (e) {
        console.error('Error parsing perms', e);
    }

    togglePermissions();
    document.getElementById('userModal').classList.add('active');
}

function closeUserModal() {
    document.getElementById('userModal').classList.remove('active');
}

function togglePermissions() {
    const role = document.getElementById('role').value;
    const group = document.getElementById('permissionsGroup');

    if (role === 'Admin') {
        group.style.opacity = '0.5';
        group.style.pointerEvents = 'none';
        // Check all visually? No, just keep them as is but denote they get Full Access
    } else {
        group.style.opacity = '1';
        group.style.pointerEvents = 'auto';
    }
}

async function saveUser(event) {
    event.preventDefault();

    const userId = document.getElementById('editUserId').value;
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;
    const role = document.getElementById('role').value;
    const status = document.getElementById('status').value;

    // Get permissions
    const permissions = [];
    if (role === 'Admin') {
        permissions.push('*');
    } else {
        document.querySelectorAll('input[name="permissions"]:checked').forEach(cb => {
            permissions.push(cb.value);
        });
    }

    const payload = {
        username,
        role,
        permissions,
        status: userId ? status : 'Active'
    };

    if (password) {
        payload.password = password;
    }

    try {
        if (userId) {
            await app.apiPut(`/users/${userId}`, payload);
            app.showNotification('User updated successfully', 'success');
        } else {
            if (!password) {
                app.showNotification('Password is required for new users', 'error');
                return;
            }
            await app.apiPost('/users', payload);
            app.showNotification('User created successfully', 'success');
        }
        closeUserModal();
        loadUsers();
    } catch (error) {
        console.error('Error saving user:', error);
        app.showNotification('Failed to save user', 'error');
    }
}

async function deleteUser(userId) {
    if (confirm('Are you sure you want to delete this user? This action cannot be undone.')) {
        try {
            await app.apiDelete(`/users/${userId}`);
            app.showNotification('User deleted successfully', 'success');
            loadUsers();
        } catch (error) {
            console.error('Error deleting user:', error);
            app.showNotification('Failed to delete user', 'error');
        }
    }
}
