@page "/management/users"

@using System.IdentityModel.Claims
@using Hcs.WebApp.Components.Dialogs
@using Hcs.WebApp.Services
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Identity
@using Microsoft.EntityFrameworkCore

@attribute [Authorize]

@inject AuthenticationStateProvider AuthenticationStateProvider
@inject UsersService UsersService
@inject DialogService DialogService

<PageTitle>Пользователи</PageTitle>

<AuthorizedContent Roles="@AppRole.ADMINISTRATOR_TYPE">
    <Content>
        <RadzenStack>
            <RadzenRow AlignItems="AlignItems.Center">
                <RadzenColumn Size="12" SizeMD="6">
                    <RadzenText Text="Пользователи" TextStyle="TextStyle.H5" class="rz-m-0" />
                </RadzenColumn>
                <RadzenColumn Size="12" SizeMD="6">
                    <RadzenStack Orientation="Orientation.Horizontal" AlignItems="AlignItems.Center" JustifyContent="JustifyContent.End" Gap="0.5rem">
                        <RadzenButton Icon="add_circle_outline" Text="Создать" Click="@AddUserAsync" ButtonStyle="ButtonStyle.Primary" />
                    </RadzenStack>
                </RadzenColumn>
            </RadzenRow>
            <RadzenRow>
                <RadzenColumn SizeMD="12">
                    <RadzenAlert Visible="@hasError" AlertStyle="AlertStyle.Danger" Variant="Variant.Flat" Shade="Shade.Lighter" AllowClose="false">
                        @errorMessage
                    </RadzenAlert>
                    <RadzenDataGrid TItem="AppUserWithRole" Data="@usersWithRoles" IsLoading="@isLoading" AllowFiltering="true" AllowPaging="true" ShowPagingSummary="true" PageSizeOptions=@(new int[] { 5, 10, 20, 30 }) AllowSorting="true">
                        <Columns>
                            <RadzenDataGridColumn TItem="AppUserWithRole" Property="User.UserName" Title="Логин" />
                            <RadzenDataGridColumn TItem="AppUserWithRole" Property="Role.Name" Title="Роль" />
                            <RadzenDataGridColumn TItem="AppUserWithRole" Filterable="false" Sortable="false" TextAlign="TextAlign.Center" Width="70px">
                                <Template Context="userWithRole">
                                    @if (userWithRole.User.Id != currentUserId)
                                    {
                                        <RadzenButton Click="@(() => EditUserAsync(userWithRole))" @onclick:stopPropagation="true" ButtonStyle="ButtonStyle.Primary" Icon="edit" Size="ButtonSize.Small" />
                                        <RadzenButton Click="@(() => DeleteUserAsync(userWithRole))" @onclick:stopPropagation="true" ButtonStyle="ButtonStyle.Danger" Icon="close" Size="ButtonSize.Small" />
                                    }
                                </Template>
                            </RadzenDataGridColumn>
                        </Columns>
                    </RadzenDataGrid>
                </RadzenColumn>
            </RadzenRow>
        </RadzenStack>
    </Content>
</AuthorizedContent>

@code {
    string currentUserId;
    IEnumerable<AppUserWithRole> usersWithRoles;
    bool isLoading;
    bool hasError;
    string errorMessage;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await base.OnAfterRenderAsync(firstRender);

        if (firstRender)
        {
            isLoading = true;

            StateHasChanged();

            var state = await AuthenticationStateProvider.GetAuthenticationStateAsync();
            if (state.User.IsAdministrator())
            {
                currentUserId = state.User.FindFirst(ClaimTypes.NameIdentifier)!.Value;
                usersWithRoles = await UsersService.GetUsersWithRoleAsync();
            }

            isLoading = false;

            StateHasChanged();
        }
    }

    async Task AddUserAsync()
    {
        var success = await DialogService.OpenAsync<AddUser>(
            "Создание пользователя",
            null,
            new DialogOptions()
            {
                Width = "420px",
                ShowClose = false,
                CloseDialogOnEsc = false,
                CloseDialogOnOverlayClick = false
            });

        if (success)
        {
            await UpdateGridAsync();
        }
    }

    async Task EditUserAsync(AppUserWithRole userWithRole)
    {
        var success = await DialogService.OpenAsync<EditUser>(
            "Редактирование пользователя",
            new Dictionary<string, object>()
            {
                { nameof(EditUser.CurrentUserId), currentUserId },
                { nameof(EditUser.UserWithRole), userWithRole }
            },
            new DialogOptions()
            {
                Width = "420px",
                ShowClose = false,
                CloseDialogOnEsc = false,
                CloseDialogOnOverlayClick = false
            });

        if (success)
        {
            await UpdateGridAsync();
        }
    }

    async Task DeleteUserAsync(AppUserWithRole userWithRole)
    {
        try
        {
            if (await DialogService.Confirm(
                GetDeleteMessage(userWithRole.User.UserName),
                "Удаление пользователя",
                new ConfirmOptions()
                {
                    OkButtonText = "Да",
                    CancelButtonText = "Отмена"
                }) == true)
            {
                isLoading = true;

                var result = await UsersService.DeleteUserAsync(userWithRole.User.Id);
                if (result.Succeeded)
                {
                    await UpdateGridAsync();
                }
                else
                {
                    isLoading = false;
                    hasError = true;
                    errorMessage = string.Join(", ", result.Errors.Select(x => x.Description));
                }
            }
        }
        catch (Exception e)
        {
            isLoading = false;
            hasError = true;
            errorMessage = e.Message;
        }
    }

    RenderFragment GetDeleteMessage(string userName)
    {
        return __builder =>
        {
            <text>
                Вы уверены что хотите удалить пользователя <b>@userName</b>?
            </text>
        };
    }

    async Task UpdateGridAsync()
    {
        isLoading = true;
        hasError = false;

        usersWithRoles = await UsersService.GetUsersWithRoleAsync();

        isLoading = false;
    }
}
