@using CouchLog.Data
@using Microsoft.AspNetCore.Identity

@inject UserManager<ApplicationUser> UserManager
@inject ISnackbar Snackbar

<MudDialog>
    <TitleContent>
        <MudText Typo="Typo.h6">Create New User</MudText>
    </TitleContent>

    <DialogContent>
        <MudInput @bind-Value="@_newUsername"></MudInput>
        <MudSelect @bind-Value="_newUserRole">
            @foreach (var role in Roles)
            {
                <MudSelectItem Value="@role.Name">@role.Name</MudSelectItem>
            }
        </MudSelect>
    </DialogContent>

    <DialogActions>
        <MudButton OnClick="CreateNewUser" Variant="Variant.Filled" Color="Color.Success">Create user</MudButton>
        <MudButton OnClick="Cancel" Variant="Variant.Filled" Color="Color.Error">Cancel</MudButton>
    </DialogActions>
</MudDialog>

@code
{
    [Parameter] public required List<IdentityRole> Roles { get; set; }
    
    [CascadingParameter]
    public IMudDialogInstance MudDialog { get; set; } = null!;
    
    private string _newUsername = string.Empty;
    private string _newUserRole = string.Empty;

    private async Task CreateNewUser()
    {
        if (string.IsNullOrWhiteSpace(_newUsername) || string.IsNullOrWhiteSpace(_newUserRole))
        {
            Snackbar.Add("Add Username and Role" , Severity.Warning);
            return;
        }

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

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

        if(result.Succeeded)
        {
            await UserManager.AddToRoleAsync(newUser, _newUserRole);
            MudDialog.Close(DialogResult.Ok(newUser));
            return;
        }

        //Snackbar.Add("User could not be created", Severity.Error);
    }

    private async Task Cancel()
    {
        MudDialog.Cancel();
    }
}