@page "/AdminSettings/UserManagement"
@rendermode InteractiveServer

@using CouchLog.Data
@using Microsoft.AspNetCore.Identity
@using Microsoft.EntityFrameworkCore
@using Microsoft.AspNetCore.Components.QuickGrid
@using Microsoft.AspNetCore.Authorization

@inject ApplicationDbContext CouchLogDB
@inject UserManager<ApplicationUser> UserManager
@inject AuthenticationStateProvider AuthenticationStateProvider
@inject NavigationManager NavigationManager

@attribute [Authorize(Roles = "Admin")]

<div class="d-flex align-items-center justify-content-between">
    <h3 class="mb-0">UserManagement</h3>

    <button type="button"
            class="btn btn-primary"
            data-bs-toggle="modal"
            data-bs-target="#exampleModal">
        Add User
    </button>
</div>

<!-- <div>
    <QuickGrid Items="@gridUsers.AsQueryable()">
        <PropertyColumn Title="#" Property="@(u => u.Index)" />
        <PropertyColumn Title="Username" Property="@(u => u.UserName)" />
        <PropertyColumn Title="Role" Property="@(u => u.Role)" />

        <TemplateColumn Title="">
            @if(context.UserId != currentUserId)
            {
                <button class="btn btn-danger btn-sm" @onclick="() => DeleteUser(context)">Delete</button>
            }
        </TemplateColumn>
    </QuickGrid>
</div> -->
<!-- #region UserCreate Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true" style="color: black">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" style="color: black" id="exampleModalLabel">Create User</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <!-- 1. Username Input mit Binding und Bootstrap Klasse -->
                <div class="mb-3">
                    <label for="newUsernameInput" class="form-label">Username:</label>
                    <input type="text" class="form-control" id="newUsernameInput" @bind="newUsername" />
                </div>

                <!-- 2. Select mit Binding -->
                <div class="mb-3">
                    <label class="form-label">Role:</label>
                    <select class="form-select" @bind="newUserRoleId">
                        <!-- WICHTIG: Eine leere Option als Standard, damit man weiß, ob etwas gewählt wurde -->
                        <option value="" selected disabled>Bitte Rolle wählen...</option>

                        @foreach (var role in roles)
                        {
                            <option value="@role.Id">@role.Name</option>
                        }
                    </select>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" @onclick="CreateUserAsync">Create User</button>
            </div>
        </div>
    </div>
</div>
<!-- #endregion -->

@code {

    string newUsername = "";
    string newUserRoleId = "";
    List<UserGridItem> gridUsers = new();
    List<IdentityRole> roles = new();
    string? currentUserId;

    protected override async Task OnInitializedAsync()
    {
        var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
        currentUserId = authState.User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value;

        var users = await CouchLogDB.Users.ToListAsync();
        roles = await CouchLogDB.Roles.ToListAsync();
        int index = 1;

        gridUsers.Clear();

        foreach (var user in users)
        {
            var role = await UserManager.GetRolesAsync(user);

            gridUsers.Add(new UserGridItem
            {
                Index = index++,
                UserId = user.Id,
                UserName = user.UserName!,
                Role = role.FirstOrDefault() ?? "-"
            });
        }
    }

    public class UserGridItem
    {
        public int Index { get; set; }
        public string UserId { get; set; } = "";
        public string UserName { get; set; } = "";
        public string Role { get; set; } = "";
    }

    async Task DeleteUser(UserGridItem user)
    {
        if (user.UserId == currentUserId)
            return;

        var identityUser = await UserManager.FindByIdAsync(user.UserId);

        if (identityUser is null)
            return;

        var result = await UserManager.DeleteAsync(identityUser);

        if (result.Succeeded)
        {
            gridUsers.Remove(user);
            StateHasChanged();
        }
        else
        {
            // Optional: Fehler anzeigen
        }
    }

    private async Task CreateUserAsync()
    {
        // Validierung
        if (string.IsNullOrWhiteSpace(newUsername) || string.IsNullOrWhiteSpace(newUserRoleId))
        {
            // Fehlermeldung anzeigen oder abbrechen
            Console.WriteLine("Bitte Benutzername und Rolle angeben.");
            return;
        }

        // Hier deine Logik zum Erstellen des Users
        var roleIdToUse = newUserRoleId;
        var usernameToUse = newUsername;

        ApplicationUser newUser = new ApplicationUser
            {
                UserName = newUsername,
                EmailConfirmed = true
            };

        var result = await UserManager.CreateAsync(newUser, "NewPassword123!");

        IdentityRole roleName = roles.FirstOrDefault(r => r.Id == newUserRoleId);

        if(result.Succeeded)
        {
            await UserManager.AddToRoleAsync(newUser, roleName.Name);
        }

        // Modal schließen oder Formular zurücksetzen
        newUsername = "";
        newUserRoleId = "";

        NavigationManager.NavigateTo(NavigationManager.Uri, true);
    }
}
