@using Microsoft.AspNetCore.Components

<main class="management-screen">
    @if (Workspace.State.IsCurrentUserAdmin)
    {
        <section class="card">
            <div class="section-head">
                <h2>Database</h2>
            </div>
            <p class="muted">Download the current SQLite file for backup or offline inspection.</p>
            <div class="management-actions">
                <a class="action-link" href="@Workspace.AdminDatabaseDownloadUrl" download>Download SQLite database</a>
            </div>
        </section>
    }
    <section class="card">
        <div class="section-head">
            <h2>User Management</h2>
        </div>
        @if (IsAdminDataLoading)
        {
            <p class="empty">Loading users...</p>
        }
        else if (!Workspace.State.IsCurrentUserAdmin)
        {
            <p class="empty">Admin role is required to manage users.</p>
        }
        else if (Workspace.State.AdminUsers.Count == 0)
        {
            <p class="empty">No users found.</p>
        }
        else
        {
            <ul class="management-list">
                @foreach (var user in Workspace.State.AdminUsers)
                {
                    <li>
                        <div>
                            <strong>@user.Username</strong>
                            <p class="muted">@user.DisplayName</p>
                            <p class="muted">Roles: @(user.Roles.Count == 0 ? "none" : string.Join(", ", user.Roles))</p>
                        </div>
                        <div class="skill-chip-actions">
                            <button type="button"
                                    class="chip-button"
                                    disabled="@(Workspace.State.IsMutating || user.Id == Workspace.State.User?.Id)"
                                    @onclick="() => Workspace.Admin.ToggleAdminRoleAsync(user)">
                                <span aria-hidden="true" class="emoji">🛡️</span>
                                <span class="sr-only">Toggle admin role for @user.Username</span>
                            </button>
                            <button type="button"
                                    class="chip-button"
                                    disabled="@(Workspace.State.IsMutating || user.Id == Workspace.State.User?.Id)"
                                    @onclick="() => Workspace.Admin.DeleteUserAsync(user)">
                                <span aria-hidden="true" class="emoji">🗑️</span>
                                <span class="sr-only">Delete user @user.Username</span>
                            </button>
                        </div>
                    </li>
                }
            </ul>
        }
    </section>
</main>

@code {
    [Parameter, EditorRequired] public WorkspacePageContext Workspace { get; set; } = null!;

    private bool IsAdminDataLoading => !Workspace.HasSessionInitialized || Workspace.State.IsAdminDataLoading;
}
