@page "/stock/productdivisions"
@using phronCare.UIBlazor.Services.Stock
@using Domain.Entities
@using Domain.Generics
@inject IToastService toastService
@inject NavigationManager Navigation
@inject ProductDivisionService productDivisionService

<div class="card">
    <div class="card-header d-flex justify-content-center align-items-center" style="zoom:80%;">
        <h3 class="card-title m-0">Divisiones de productos</h3>
    </div>
    <div class="card-body" style="zoom:80%;">
        <div class="mb-4 space-y-2">
            <input @bind="SearchParams.Term" placeholder="Descripción" class="border rounded p-1 w-full" />
            <button class="btn btn-primary rounded-pill" @onclick="Buscar">
                <i class="fas fa-search me-1"></i> Buscar
            </button>
            <button class="btn btn-success rounded-pill" @onclick="Nuevo">
                <i class="fas fa-plus me-1"></i> Nuevo
            </button>
            <button class="btn btn-secondary rounded-pill" @onclick="Volver">
                <i class="fas fa-arrow-left me-1"></i> Volver
            </button>
        </div>
        <hr />
        <div style="zoom:90%;">
            @if (Tabla != null && Tabla.Any())
            {
                <PhTable Columns="Columnas"
                         Data="Tabla"
                         SelectionField="Id"
                         RowsPerPage=SearchParams.PageSize
                         RenderButtons="true"
                         Buttons="Botones"
                         ShowPageButtons="false"
                         ShowQuickSearch="false"
                         RenderSelect="false" />
            }
            else
            {
                <p>No hay resultados.</p>
            }
        </div>
    </div>
    <div class="card-footer d-flex justify-content-center align-items-center" style="zoom:80%;">
        <div class="d-flex align-items-center gap-3">
            <button class="btn btn-secondary rounded-pill" @onclick="PrimeraPagina" disabled="@(SearchParams.Page == 1)">
                <i class="fas fa-angle-double-left me-1"></i> Primera
            </button>
            <button class="btn btn-secondary rounded-pill" @onclick="AnteriorPagina" disabled="@(!PuedeRetroceder)">
                <i class="fas fa-chevron-left me-1"></i> Anterior
            </button>
            <span class="mx-2">
                Página <strong>@SearchParams.Page</strong> de <strong>@TotalPaginas</strong>
            </span>
            <button class="btn btn-secondary rounded-pill" @onclick="SiguientePagina" disabled="@(!PuedeAvanzar)">
                Siguiente <i class="fas fa-chevron-right ms-1"></i>
            </button>
            <button class="btn btn-secondary rounded-pill" @onclick="UltimaPagina" disabled="@(SearchParams.Page == TotalPaginas)">
                Última <i class="fas fa-angle-double-right ms-1"></i>
            </button>
            <div class="d-flex align-items-center ms-3">
                <input type="number" class="form-control form-control-sm rounded" style="width: 80px;" min="1" max="@TotalPaginas" @bind="PaginaDeseada" />
                <button class="btn btn-outline-primary btn-sm ms-2 rounded-pill" @onclick="IrAPagina">
                    <i class="fas fa-arrow-right-to-bracket me-1"></i> Ir
                </button>
            </div>
        </div>
    </div>
</div>

@code {
    private PagedResult<ELSProductDivision>? Resultado;
    private List<Dictionary<string, object>> Tabla = new();
    private List<string> Columnas = new() { "Id", "Codigo", "Nombre", "Descripción" };
    private DivisionUnitSearchParams SearchParams = new() { PageSize = 10 };
    private List<PhTable.ButtonOptions> Botones;
    private int PaginaDeseada = 1;

    protected override void OnInitialized()
    {
        Botones = new List<PhTable.ButtonOptions>
        {
            new PhTable.ButtonOptions
            {
                Caption = "<i class='fas fa-pen'></i>",
                ElementClass = "btn btn-success",
                UrlAction = "/stock/productdivisionform/",
                OnClickAction = async (id) =>
                {
                    Navigation.NavigateTo($"/stock/productdivisionform/{id}");
                }
            }

        };
    }

    private async Task Buscar()
    {
        SearchParams.Page = 1;
        await CargarPaginaActual();
    }

    private async Task CargarPaginaActual()
    {
        Resultado = await productDivisionService.SearchAsync(SearchParams);
        if (Resultado?.Items != null)
        {
            Tabla = Resultado.Items.Select(d => new Dictionary<string, object>
        {
            { "Id", d.Id },
            { "Codigo", d.Code ?? string.Empty },
            { "Nombre", d.Name ?? string.Empty },
            { "Descripción", d.Description ?? string.Empty }
        }).ToList();
        }
    }

    private async Task PrimeraPagina() { SearchParams.Page = 1; await CargarPaginaActual(); }
    private async Task UltimaPagina() { SearchParams.Page = TotalPaginas; await CargarPaginaActual(); }
    private async Task SiguientePagina() => await CambiarPagina(1);
    private async Task AnteriorPagina() => await CambiarPagina(-1);

    private async Task CambiarPagina(int delta)
    {
        var nuevaPagina = SearchParams.Page + delta;
        if (nuevaPagina >= 1 && nuevaPagina <= TotalPaginas)
        {
            SearchParams.Page = nuevaPagina;
            await CargarPaginaActual();
        }
    }
     private int TotalPaginas => Resultado == null || Resultado.TotalItems == 0
        ? 1
        : (int)Math.Ceiling((double)(Resultado.TotalItems) / SearchParams.PageSize);
   private async Task IrAPagina()
    {
        if (PaginaDeseada >= 1 && PaginaDeseada <= TotalPaginas)
        {
            SearchParams.Page = PaginaDeseada;
            await Buscar();
        }
        else
        {
            toastService.ShowWarning("Número de página fuera de rango.");
        }
    }

    private void Nuevo() => Navigation.NavigateTo("/stock/productdivisionform/");
    private void Volver() => Navigation.NavigateTo("/DashboardPanel");

    private bool PuedeRetroceder => Resultado != null && SearchParams.Page > 1;
    private bool PuedeAvanzar => Resultado != null && SearchParams.Page < TotalPaginas;
    // private int TotalPaginas => Resultado is null ? 1 :
    //     (int)Math.Ceiling((double)(Resultado.TotalItems) / SearchParams.PageSize);
}
