@using JSMR.UI.Blazor.Enums

<div class="pagination">
    <div>
        <label>@IndexInfo</label>
    </div>
    <MudPagination class="pager" ShowFirstButton="true" ShowLastButton="true" Count="@((int)Math.Ceiling((decimal)TotalItems / (decimal)PageSize))" Selected="@PageNumber" SelectedChanged="OnSelectedChanged" />
    <div class="page-sizes">
        @RightContent
        <BitDropdown Items="PageSizes2"
                     Style="min-width: 7rem"
                     Placeholder="Select..."
                     TItem="BitDropdownItem<int>"
                     TValue="int"
                     Value="PageSize"
                     ValueChanged="OnPageSizeChanged">
            <PrefixTemplate>
                <InputPrefix Graphic="Graphic.Grid" Tooltip="Page Size"></InputPrefix>
            </PrefixTemplate>
        </BitDropdown>
    </div>
</div>

@code {
    [Parameter]
    public int PageNumber { get; set; }

    [Parameter]
    public EventCallback<int> PageNumberChanged { get; set; }

    [Parameter]
    public int[] PageSizes { get; set; } = [5, 10, 25, 50, 100];

    List<BitDropdownItem<int>> PageSizes2 => [.. PageSizes.Select(x => new BitDropdownItem<int>() { Text = x.ToString(), Value = x })];

    [Parameter]
    public int PageSize { get; set; }

    [Parameter]
    public EventCallback<int> PageSizeChanged { get; set; }

    [Parameter]
    public int TotalItems { get; set; }

    [Parameter]
    public EventCallback<int> TotalItemsChanged { get; set; }

    [Parameter]
    public RenderFragment? RightContent { get; set; }

    public string IndexInfo => TotalItems == 0 ? "No items" : $"{StartIndex.ToString("n0")} - {EndIndex.ToString("n0")} of {TotalItems.ToString("n0")} items";

    public int StartIndex => (PageNumber - 1) * PageSize + 1;
    public int EndIndex => PageNumber * PageSize < TotalItems ? PageNumber * PageSize : TotalItems;

    private async Task OnSelectedChanged(int newPage)
    {
        PageNumber = newPage;
        await PageNumberChanged.InvokeAsync(newPage);
    }

    private async Task OnPageSizeChanged(int newPageSize)
    {
        PageSize = newPageSize;
        await PageSizeChanged.InvokeAsync(newPageSize);
    }
}