using Microsoft.AspNetCore.Components;
using Blazorise.DataGrid;
using Blazor.ViewClasses;
using Blazor.Modals;
using Blazored.LocalStorage;
using Blazored.Modal.Services;
using Blazor.Services;
using Blazored.Modal;
using Microsoft.Extensions.Localization;

namespace Blazor.Pages.Admins;

public partial class Administrators
{
    public List<Administrator> administrators = new();

    private int totalItem;

    [CascadingParameter]
    public required IModalService Modal { get; set; }

    [Inject]
    public IStringLocalizer<Administrators> Localizer { get; set; }

    [Inject]
    public required IDataService DataService { get; set; }

    [Inject]
    public required IWebHostEnvironment WebHostEnvironment { get; set; }

    [Inject]
    public required ILocalStorageService LocalStorage { get; set; }

    [Inject]
    public required HttpClient Http { get; set; }

    [Inject]
    public required NavigationManager NavigationManager { get; set; }

    private async Task OnReadData(DataGridReadDataEventArgs<Administrator> e)
    {
        if (e.CancellationToken.IsCancellationRequested)
        {
            return;
        }
        // Calculez l'index de départ pour la pagination
        int page = ((e.Page - 1) * e.PageSize) / 10 + 1;

        // Envoyez une requête à l'API pour récupérer les questions de la page actuelle
        var response = await Http.GetFromJsonAsync<Administrator[]>(API.API_URL + "all/administrators/" + API.TOKEN + "/" + page);

        if (!e.CancellationToken.IsCancellationRequested && response != null)
        {
            administrators = new List<Administrator>(response); // an actual data for the current page
            totalItem = response[0].total_administrators;
        }
    }

    private async void OnDelete(int id)
    {
        var parameters = new ModalParameters();
        parameters.Add(nameof(Administrator.Id), id);

        var modal = Modal.Show<DeleteConfirmation>("Delete Confirmation", parameters);
        var result = await modal.Result;

        if (result.Cancelled)
        {
            return;
        }

        string apiUri = API.API_URL +"delete/administrator/" + id + "/" + API.TOKEN;

        using (var httpClient = new HttpClient())
        {
            var response = await httpClient.DeleteAsync(apiUri);

            if (response.IsSuccessStatusCode)
            {
                var responseBody = await response.Content.ReadAsStringAsync();
            }
            else
            {
                var errorResponse = await response.Content.ReadAsStringAsync();
            }
        }

        NavigationManager.NavigateTo("administrators", true);
    }
}
