{% extends "base.html" %}

{% block title %}Users - AtlasUI{% endblock %}

{% block content %}
<div class="row">
    <div class="col-12">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h1><i class="bi bi-people"></i> Database Users</h1>
            <div>
                <select class="form-select form-select-sm d-inline-block w-auto me-2" id="projectSelect">
                    <option value="">Select a project...</option>
                </select>
                <button class="btn btn-outline-success btn-sm" id="refreshBtn">
                    <i class="bi bi-arrow-clockwise"></i> Refresh
                </button>
            </div>
        </div>

        <!-- Info message -->
        <div class="alert alert-info" role="alert">
            <i class="bi bi-info-circle"></i>
            Select a project to view its database users.
        </div>

        <!-- Loading indicator -->
        <div id="loadingIndicator" class="text-center my-5 d-none">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
            <p class="mt-2">Loading users...</p>
        </div>

        <!-- Error message -->
        <div id="errorMessage" class="alert alert-danger d-none" role="alert">
            <i class="bi bi-exclamation-triangle"></i>
            <span id="errorText"></span>
        </div>

        <!-- Users table -->
        <div id="usersTable" class="d-none">
            <div class="table-responsive">
                <table class="table table-striped table-hover">
                    <thead>
                        <tr>
                            <th>Username</th>
                            <th>Database</th>
                            <th>Roles</th>
                            <th>Scopes</th>
                        </tr>
                    </thead>
                    <tbody id="usersBody">
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
let projects = [];
let users = [];

document.addEventListener('DOMContentLoaded', function() {
    loadProjects();
    document.getElementById('projectSelect').addEventListener('change', handleProjectChange);
    document.getElementById('refreshBtn').addEventListener('click', handleRefresh);
});

async function loadProjects() {
    try {
        // Fetch all organizations
        const orgsResponse = await fetch('/api/organizations/');
        if (!orgsResponse.ok) throw new Error('Failed to fetch organizations');
        const orgsData = await orgsResponse.json();

        // Fetch projects for each organization
        projects = [];
        for (let org of orgsData.results || []) {
            const projectsResponse = await fetch(`/api/organizations/${org.id}/projects?itemsPerPage=500`);
            if (projectsResponse.ok) {
                const projectsData = await projectsResponse.json();
                projects = projects.concat(projectsData.results || []);
            }
        }

        renderProjectOptions();

    } catch (err) {
        console.error('Error loading projects:', err);
        document.getElementById('errorMessage').classList.remove('d-none');
        document.getElementById('errorText').textContent = 'Failed to load projects: ' + err.message;
    }
}

function renderProjectOptions() {
    const select = document.getElementById('projectSelect');
    const currentValue = select.value;

    // Clear existing options except the first one
    select.innerHTML = '<option value="">Select a project...</option>';

    projects.forEach(project => {
        const option = document.createElement('option');
        option.value = project.id;
        option.textContent = project.name;
        select.appendChild(option);
    });

    if (currentValue) {
        select.value = currentValue;
    }
}

async function handleProjectChange(e) {
    const projectId = e.target.value;

    if (!projectId) {
        document.getElementById('usersTable').classList.add('d-none');
        return;
    }

    await loadUsers(projectId);
}

async function handleRefresh() {
    const projectId = document.getElementById('projectSelect').value;
    if (projectId) {
        await loadUsers(projectId);
    } else {
        await loadProjects();
    }
}

async function loadUsers(projectId) {
    const loading = document.getElementById('loadingIndicator');
    const error = document.getElementById('errorMessage');
    const table = document.getElementById('usersTable');

    loading.classList.remove('d-none');
    error.classList.add('d-none');
    table.classList.add('d-none');

    try {
        const response = await fetch(`/api/users/${projectId}`);
        if (!response.ok) throw new Error('Failed to fetch users');

        const data = await response.json();
        users = data.results || [];

        renderUsers();
        loading.classList.add('d-none');
        table.classList.remove('d-none');

    } catch (err) {
        console.error('Error loading users:', err);
        loading.classList.add('d-none');
        error.classList.remove('d-none');
        document.getElementById('errorText').textContent = err.message;
    }
}

function renderUsers() {
    const tbody = document.getElementById('usersBody');
    tbody.innerHTML = '';

    if (users.length === 0) {
        tbody.innerHTML = '<tr><td colspan="4" class="text-center text-muted">No users found in this project</td></tr>';
        return;
    }

    users.forEach(user => {
        const row = document.createElement('tr');

        const roles = user.roles || [];
        const scopes = user.scopes || [];

        row.innerHTML = `
            <td><strong>${user.username}</strong></td>
            <td><code>${user.databaseName || 'admin'}</code></td>
            <td>
                ${roles.length > 0 ?
                    roles.map(role => `<span class="badge bg-primary me-1">${role.roleName}@${role.databaseName}</span>`).join('') :
                    '<span class="text-muted">No roles</span>'
                }
            </td>
            <td>
                ${scopes.length > 0 ?
                    scopes.map(scope => `<span class="badge bg-secondary me-1">${scope.type}: ${scope.name}</span>`).join('') :
                    '<span class="text-muted">No scopes</span>'
                }
            </td>
        `;
        tbody.appendChild(row);
    });
}
</script>
{% endblock %}
