@page "/AdminSettings/UserManagement"
@rendermode InteractiveServer

@using CouchLog.Components.AdminSettings.Pages.Dialogs
@using CouchLog.Data
@using Microsoft.AspNetCore.Identity
@using Microsoft.EntityFrameworkCore
@using Microsoft.AspNetCore.Authorization

@inject ApplicationDbContext CouchLogDb
@inject UserManager<ApplicationUser> UserManager
@inject AuthenticationStateProvider AuthenticationStateProvider
@inject NavigationManager NavigationManager
@inject IDialogService DialogService
@inject ISnackbar Snackbar

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

<MudStack Row="true">
    <MudText Typo="Typo.h3">UserManagement</MudText>
    <MudSpacer/>
    <MudFab StartIcon="@Icons.Material.Filled.Add" Color="Color.Primary" OnClick="OpenCreateUserDialog"/>
</MudStack>

<br/>

<MudDataGrid Items="_gridUsers" Filterable="false" SortMode="@SortMode.Single" Groupable="false">
    <Columns>
        <PropertyColumn Property="arg => arg.Index " Title="Index"/>
        <PropertyColumn Property="arg => arg.UserId" Title="User Id"/>
        <PropertyColumn Property="arg => arg.UserName" Title="User Name"/>
        <PropertyColumn Property="arg => arg.Role" Title="Role"/>
        <TemplateColumn>
            <CellTemplate>
                @if (context.Item.UserId != _currentUserId)
                {
                    <MudFab Color="Color.Error" StartIcon="@Icons.Material.Filled.Delete" OnClick="@(() => DeleteUser(context.Item))"/>
                }
            </CellTemplate>
        </TemplateColumn>
    </Columns>
</MudDataGrid>

@code {
    private string? _currentUserId;
    private List<ApplicationUser> _users = new();
    private List<IdentityRole> _roles = new();
    private List<UserGridItem> _gridUsers = new();
    
    public class UserGridItem
    {
        public int Index { get; set; }
        public string UserId { get; set; } = "";
        public string UserName { get; set; } = "";
        public string Role { get; set; } = "";
    }

    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();

        await CreateGridUserObjects();
    }

    private async Task CreateGridUserObjects()
    {
        _gridUsers.Clear();
        
        var users = await CouchLogDb.Users.ToListAsync();
        int index = 1;
        
        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() ?? "-"
            });
        }
    }

    private async Task OpenCreateUserDialog()
    {
        var parameters = new DialogParameters<CreateUserDialog>
        {
            { x => x.Roles, _roles }
        };
        
        var dialog = await DialogService.ShowAsync<CreateUserDialog>("Create User", parameters);
        var result = await dialog.Result;
        if (!result!.Canceled && result.Data is ApplicationUser newUser)
        {
            Snackbar.Add("User created", Severity.Success);
            await CreateGridUserObjects();
            StateHasChanged();
        }
    }

    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
        {
            Snackbar.Add(result.Errors.ToString()!, Severity.Warning);
        }
    }
}
