@page "/sales/institutions"
@using phronCare.UIBlazor.Services.Sales
@using Domain.Entities
@using Domain.Generics
@using Domain.SearchParams
@inject IToastService toastService
@inject NavigationManager Navigation
@inject InstitutionService institutionService

<div class="card">
    <div class="card-header d-flex justify-content-center align-items-center" style="zoom:80%;">
        <h3 class="card-title m-0">Búsqueda de instituciones</h3>
    </div>
    <div class="card-body" style="zoom:80%;">
        <div class="mb-4 space-y-2">
            <input @bind="SearchParams.Name" placeholder="Nombre de la institución" class="border rounded p-1 w-full" />
            <input @bind="SearchParams.Type" placeholder="Tipo (Hospital, Clínica...)" class="border rounded p-1 w-full" />
            <input @bind="SearchParams.Province" placeholder="Provincia de la institución" class="border rounded p-1 w-full" />
            <button class="btn btn-primary rounded-pill" @onclick="BuscarInstituciones">
                <i class="fas fa-binoculars me-1"></i> Buscar
            </button>
            <button class="btn btn-success rounded-pill" @onclick="NuevaInstitucion">
                <i class="fas fa-plus me-1"></i> Nueva
            </button>
            <button class="btn btn-success rounded-pill" @onclick="ExportarExcel">
                <i class="fas fa-file-excel me-1"></i> Excel
            </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:0.8;">
            @if (TablaInstituciones != null && TablaInstituciones.Any())
            {
                <PhTable Columns="TableColumns"
                         Data="TablaInstituciones"
                         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 InstitutionSearchParams SearchParams = new();
    private PagedResult<EInstitution>? PagedResult;
    private List<Dictionary<string, object>> TablaInstituciones = new();
    private List<string> TableColumns = new()
    {
        "Id", "Nombre", "Tipo", "Dirección", "Ciudad", "Provincia", "Teléfono", "Email", "Activo"
    };
    private int PaginaDeseada = 1;

    private List<PhTable.ButtonOptions> botones;

    protected override void OnInitialized()
    {
        botones = new List<PhTable.ButtonOptions>
        {
            new PhTable.ButtonOptions
            {
                Caption = "Editar",
                ElementClass = "btn btn-primary btn-sm",
                UrlAction = "/sales/institutionform/",
                OnClickAction = async (id) =>
                {
                    if (int.TryParse(id, out var instId))
                    {
                        Navigation.NavigateTo($"/sales/institutionform/{instId}");
                    }
                }
            }
        };
    }

    private async Task BuscarInstituciones() => await CargarInstituciones();

    private async Task CargarInstituciones()
    {
        PagedResult = await institutionService.SearchInstitutionsAsync(SearchParams);
        if (PagedResult?.Items is not null)
        {
            TablaInstituciones = PagedResult.Items.Select(i => new Dictionary<string, object>
            {
                { "Id", i.Id },
                { "Nombre", i.Name ?? string.Empty },
                { "Tipo", i.Type ?? string.Empty },
                { "Dirección", i.Streetaddress ?? string.Empty },
                { "Ciudad", i.City ?? string.Empty },
                { "Provincia", i.Province ?? string.Empty },
                { "Teléfono", i.Phone ?? string.Empty },
                { "Email", i.Email ?? string.Empty },
                { "Activo", i.Isactive ? "Sí" : "No" }
            }).ToList();
        }
    }

    private async Task PrimeraPagina() { SearchParams.Page = 1; await BuscarInstituciones(); }
    private async Task UltimaPagina() { SearchParams.Page = TotalPaginas; await BuscarInstituciones(); }
    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 BuscarInstituciones();
        }
    }

    private async Task IrAPagina()
    {
        if (PaginaDeseada >= 1 && PaginaDeseada <= TotalPaginas)
        {
            SearchParams.Page = PaginaDeseada;
            await BuscarInstituciones();
        }
        else
        {
            toastService.ShowWarning("Número de página fuera de rango.");
        }
    }

    private async Task ExportarExcel()
    {
        var exportParams = new InstitutionSearchParams
            {
                Name = SearchParams.Name,
                Type = SearchParams.Type,
                Province = SearchParams.Province,
                Page = 1,
                PageSize = int.MaxValue
            };

        try
        {
            await institutionService.ExportFilteredAsync(exportParams);
            toastService.ShowSuccess("Exportación completada exitosamente.");
        }
        catch (Exception ex)
        {
            toastService.ShowError($"{ex.Message}");
        }
    }

    private void NuevaInstitucion() => Navigation.NavigateTo("/sales/institutionform/");
    private void Volver() => Navigation.NavigateTo("/DashboardPanel");

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