@page "/role/{id}"
@page "/role/create"

@using System.Net.Http.Headers;
@using System.Text.Json;

@inject HttpClient _httpClient
@inject NavigationManager Navigation
@inject IToastService toastService
@inject AuthenticationStateProvider authenticationStateProvider

@if (role.Id is null)
{
    <h1>Crear Nuevo Rol</h1>
}
else
{
    <h1>Editar Rol</h1>
}
@if (role is not null)
{
    <EditForm Model="role" OnValidSubmit="UpsertRole">
        <DataAnnotationsValidator />
        <ValidationSummary />

        <div class="form-group">
            <label for="Name">Id del Rol</label>
            <InputText disabled="1" @bind-Value="role.Id" id="Id" class="form-control" />
        </div>

        <div class="form-group">
            <label for="Name">Nombre del Rol</label>
            <InputText @bind-Value="role.Name" id="Name" class="form-control" />
        </div>

        <div class="form-group">
            <label for="NormalizedName">Nombre Normalizado</label>
            <InputText disabled="1" @bind-Value="role.NormalizedName" id="NormalizedName" class="form-control" />
        </div>
        <br/>
        <div class="form-group">
            <button type="submit" class="btn btn-primary">Guardar</button>
            <button type="button" class="btn btn-secondary" @onclick="Cancel">Cancelar</button>
        </div>
    </EditForm>
}
@code {
    [Parameter]
    public string id { get; set; } = string.Empty;
    private Role? role;
    protected override async Task OnInitializedAsync()
    {
        if ( id is not null)
        {
            role = await GetRole(id);
        }
        else
        {
            role = new Role();
        }
    }

    public async Task<Role?> GetRole(string roleId)
    {
        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/GetRoleById/"+roleId);

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

    }
    private async Task UpsertRole()
    {
        if(role.Id is null)
        {
            await CreateRole();
        }
        else
        {
            await UpdateRole();
        }
    }
    public async Task UpdateRole()
    {
        if (role == null)
        {
            toastService.ShowError("Role no está definido.");
            return;
        }

        var requestContent = new StringContent(JsonSerializer.Serialize(role), System.Text.Encoding.UTF8, "application/json");
        var response = await _httpClient.PutAsync("/api/Account/UpdateRole/" + role.Id, requestContent);

        if (response.IsSuccessStatusCode)
        {
            toastService.ShowSuccess("El registro fue actualizado correctamente!");
            Navigation.NavigateTo("/roles"); // Redirige a la página de roles después de la actualización
        }
        else
        {
            // Manejar errores de actualización
            var errorResponse = await response.Content.ReadAsStringAsync();
            toastService.ShowError(errorResponse);
        }
    }

    public async Task CreateRole()
    {
        var newConcurrencyStamp = Guid.NewGuid().ToString();
        var requestContent = new StringContent(JsonSerializer.Serialize(role), System.Text.Encoding.UTF8, "application/json");
        var response = await _httpClient.PostAsync("/api/Account/CreateRole/", requestContent);
        var errorResponse = await response.Content.ReadAsStringAsync();
        if (response.IsSuccessStatusCode)
        {
            toastService.ShowSuccess(errorResponse);
            Navigation.NavigateTo("/roles"); // Redirige a la página de roles después de la actualización
        }
        else
        {
            toastService.ShowError(errorResponse);
        }
    }

    public void Cancel()
    {
        Navigation.NavigateTo("/roles");
    }

    public class Role
    {
        public string? Id { get; set; }
        public string? Name { get; set; }
        public string? NormalizedName { get; set; }
        public string? ConcurrencyStamp { get; set; }
    }
}