@page "/roles/deleteuser/{id}"

@using Microsoft.AspNetCore.Components
@using System.Threading.Tasks
@using System.Net.Http.Headers;
@using System.Text.Json;

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

<p>¿Estás seguro de que deseas eliminar este usuario?</p>

<button class="btn btn-danger" @onclick="ConfirmDelete">Aceptar</button>
<button class="btn btn-secondary" @onclick="CancelDelete">Cancelar</button>

@code {
    [CascadingParameter] BlazoredModalInstance BlazoredModal { get; set; } = default!;
    [Parameter]
    public string id { get; set; } = string.Empty;
    [Parameter] public EventCallback OnDeleteConfirmed { get; set; }

    private async Task ConfirmDelete()
    {
        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.DeleteAsync("/api/Account/DeleteUser/" + id);
                var jsonResponse = await response.Content.ReadAsStringAsync();
                if (response.IsSuccessStatusCode)
                {
                    toastService.ShowSuccess(jsonResponse);
                    await OnDeleteConfirmed.InvokeAsync();
                }
                else
                {
                    toastService.ShowError(jsonResponse);
                }
            }
            catch (Exception ex)
            {
                toastService.ShowError(ex.Message);
            }
        }
        Navigation.NavigateTo("/users");
    }

    private void CancelDelete()
    {
        Navigation.NavigateTo("/users");
    }
}