@page "/roles"
@using System.Net.Http.Headers;
@using System.Text.Json;

@inject HttpClient _httpClient
@inject NavigationManager navigation
@inject IToastService toastService

@inject IModalService modalService
@inject AuthenticationStateProvider authenticationStateProvider

<h1>Lista de Roles</h1>
<a href="/role/create" class="btn btn-dark">Crear Nuevo Rol</a>
<br/>
@if (roles != null && roles.Count > 0)
{
    <table class="table">
        <thead>
            <tr>
                <th>Id</th>
                <th>Name</th>
                <th>NormalizedName</th>
                <th>ConcurrencyStamp</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var role in roles)
            {
                <tr>
                    <td>@role.Id</td>
                    <td>@role.Name</td>
                    <td>@role.NormalizedName</td>
                    <td>@role.ConcurrencyStamp</td>
                    <td>
                        <button class="btn btn-primary btn-margin" @onclick="() => EditRole(role.Id)"> <span class="oi oi-pencil"></span> </button>
                        @if (role.Name != "Admin")
                        {
                            <button class="btn btn-danger btn-margin" @onclick="() => ConfirmDelete(role.Id)"> <span class="oi oi-trash"></span> </button>
                        }
                    </td>
                </tr>
            }
        </tbody>
    </table>
}
else
{
    <br />
    <p>Cargando informacion...</p>
}

@code {
    private List<Role> roles =new List<Role>();
    protected override async Task OnInitializedAsync()
    {
        var customAuthStateProvider = (CustomAuthorizationProvider)authenticationStateProvider;
        var token = await customAuthStateProvider.GetTokenData();
        if (!string.IsNullOrWhiteSpace(token.token))
        {
            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.token);
            try
            {
                var response = await _httpClient.GetAsync("/api/Account/GetAllRoles");
                if (response.IsSuccessStatusCode)
                {
                    var jsonResponse = await response.Content.ReadAsStringAsync();
                    var options = new JsonSerializerOptions
                        {
                            PropertyNameCaseInsensitive = true
                        };
                    roles = JsonSerializer.Deserialize<List<Role>>(jsonResponse, options) ?? new List<Role>();
                }
            }
            catch (Exception ex)
            {
                toastService.ShowError(ex.Message);
            }
        }
    }
    private async Task HandleDeleteConfirmed()
    {
        await RefreshRoles();
    }
    public async Task RefreshRoles()
    {
        var response = await _httpClient.GetAsync("/api/Account/GetAllRoles");

        if (response.IsSuccessStatusCode)
        {
            var jsonResponse = await response.Content.ReadAsStringAsync();
            var options = new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true
                };
            roles = JsonSerializer.Deserialize<List<Role>>(jsonResponse, options) ?? new List<Role>();

            StateHasChanged();
        }
    }
    public void EditRole(string roleId)
    {
        navigation.NavigateTo($"/role/{roleId}");
    }
    private void ConfirmDelete(string roleId)
    {
        var parameters = new ModalParameters()
                    .Add(nameof(DeleteRole.id), roleId)
                    .Add(nameof(DeleteRole.OnDeleteConfirmed), EventCallback.Factory.Create(this,HandleDeleteConfirmed));
        modalService.Show <DeleteRole> ("Confirmar Eliminación de Rol", parameters);
    }
    public class Role
    {
        public string Id { get; set; } = string.Empty;
        public string Name { get; set; } = string.Empty;
        public string NormalizedName { get; set; } = string.Empty;
        public string ConcurrencyStamp { get; set; } = string.Empty;
    }
}