@using Hcs.WebApp.Services
@using Microsoft.AspNetCore.Identity
@using Microsoft.EntityFrameworkCore

@inject UserManager<AppUser> UserManager;
@inject RoleManager<AppRole> RoleManager
@inject UsersService UsersService
@inject DialogService DialogService

<RadzenTemplateForm TItem="InputModel" Data=@Input Submit="@DoEditUserAsync">
    <RadzenAlert Visible="@hasError" AlertStyle="AlertStyle.Danger" Variant="Variant.Flat" Shade="Shade.Lighter" AllowClose="false">
        @errorMessage
    </RadzenAlert>
    <RadzenStack Gap="1rem" class="rz-p-sm-4">
        <RadzenFormField Text="Логин" Variant="Variant.Outlined">
            <ChildContent>
                <RadzenTextBox Name="UserName" @bind-Value=@Input.UserName Disabled="true" />
            </ChildContent>
        </RadzenFormField>
        <RadzenFormField Text="Роль" Variant="Variant.Outlined">
            <ChildContent>
                <RadzenDropDown Data="@roles" TextProperty="Name" ValueProperty="Id" @bind-Value="@Input.RoleId" Disabled="@Input.RoleDisabled" Name="Role" style="width: 100%" />
            </ChildContent>
        </RadzenFormField>
        <RadzenFormField Text="Новый пароль" Variant="Variant.Outlined">
            <ChildContent>
                <RadzenPassword Name="Password" @bind-Value=@Input.Password AutoCompleteType="AutoCompleteType.NewPassword" />
            </ChildContent>
            <Helper>
                @if (!string.IsNullOrEmpty(Input.Password))
                {
                    <RadzenLengthValidator Component="Password" Min="6" Text="Длина поля 'Новый пароль' должна быть не меньше 6" />
                    <RadzenLengthValidator Component="Password" Max="100" Text="Длина поля 'Новый пароль' должна быть не больше 100" />
                }
            </Helper>
        </RadzenFormField>
        <RadzenFormField Text="Повторите новый пароль" Variant="Variant.Outlined">
            <ChildContent>
                <RadzenPassword Name="ConfirmPassword" @bind-Value=@Input.ConfirmPassword AutoCompleteType="AutoCompleteType.NewPassword" />
            </ChildContent>
            <Helper>
                <RadzenCompareValidator Value=@Input.Password Component="ConfirmPassword" Text="Пароли должны совпадать" />
            </Helper>
        </RadzenFormField>
        <RadzenStack Orientation="Orientation.Horizontal" AlignItems="AlignItems.Center" JustifyContent="JustifyContent.End" Gap="0.5rem">
            <RadzenButton ButtonType="ButtonType.Submit" Disabled="@inProgress" Text="Сохранить"></RadzenButton>
            <RadzenButton Click="@DoClose" ButtonStyle="ButtonStyle.Light" Disabled="@inProgress" Text="Отмена"></RadzenButton>
        </RadzenStack>
    </RadzenStack>
</RadzenTemplateForm>

@code {
    sealed class InputModel
    {
        public string UserName { get; set; }

        public bool RoleDisabled { get; set; }

        public string RoleId { get; set; }

        public string Password { get; set; } = "";

        public string ConfirmPassword { get; set; } = "";
    }

    IEnumerable<AppRole> roles;
    bool inProgress;
    bool hasError;
    string errorMessage;

    [Parameter]
    public required string CurrentUserId { get; set; }

    [Parameter]
    public required AppUserWithRole UserWithRole { get; set; }

    [SupplyParameterFromForm]
    InputModel Input { get; set; } = new();

    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();

        Input.UserName = UserWithRole.User.UserName;
        Input.RoleDisabled = CurrentUserId == UserWithRole.User.Id;
        Input.RoleId = UserWithRole.Role.Id;

        roles = await RoleManager.Roles.OrderBy(x => x.Priority).ToListAsync();
    }

    async Task DoEditUserAsync(InputModel input)
    {
        if (inProgress) return;

        inProgress = true;
        hasError = false;

        try
        {
            await UsersService.UpdateUserAsync(UserWithRole.User.Id, input.RoleId, input.Password);

            DialogService.Close(true);
        }
        catch (Exception e)
        {
            hasError = true;
            errorMessage = e.Message;
        }
        finally
        {
            inProgress = false;
        }
    }

    void DoClose()
    {
        if (inProgress) return;

        DialogService.Close(false);
    }
}
