@namespace Lumeo
@typeparam TItem
@inject Lumeo.Services.Localization.ILumeoLocalizer L

@if (Context is not null)
{
    <div data-slot="datagrid-pagination" class="@CssClass" @attributes="AdditionalAttributes">
        @if (PageSizeOptions is { Length: > 0 })
        {
            <div class="flex items-center gap-2 text-sm text-muted-foreground whitespace-nowrap">
                <span class="text-xs">@L["Pagination.RowsPerPage"]</span>
                <Select Value="@Context.PageSize.ToString()" ValueChanged="@OnPageSizeSelected">
                    <SelectTrigger Class="h-8 w-[70px]">
                        <span class="text-sm">@Context.PageSize</span>
                    </SelectTrigger>
                    <SelectContent>
                        @foreach (var size in PageSizeOptions)
                        {
                            <SelectItem Value="@size.ToString()">@size</SelectItem>
                        }
                    </SelectContent>
                </Select>
            </div>
        }

        <div class="ml-auto flex items-center gap-4 text-sm text-muted-foreground whitespace-nowrap">
            <span class="tabular-nums">@L["Pagination.RangeOfTotal", StartItem, EndItem, Context.TotalCount]</span>
            <Pagination Class="!mx-0 !w-auto">
                <PaginationContent>
                    <PaginationPrevious OnClick="@GoToPrevious" Disabled="@(Context.CurrentPage <= 1)" />
                    @foreach (var page in GetPageNumbers())
                    {
                        if (page == -1)
                        {
                            <PaginationEllipsis />
                        }
                        else
                        {
                            var pageNum = page;
                            <PaginationItem IsActive="@(pageNum == Context.CurrentPage)" OnClick="@(() => GoToPage(pageNum))">
                                @(pageNum)
                            </PaginationItem>
                        }
                    }
                    <PaginationNext OnClick="@GoToNext" Disabled="@(Context.CurrentPage >= TotalPages)" />
                </PaginationContent>
            </Pagination>
        </div>
    </div>
}

@code {
    [CascadingParameter] private DataGridContext<TItem>? Context { get; set; }
    [Parameter] public EventCallback<int> PageChanged { get; set; }
    [Parameter] public EventCallback<int> PageSizeChanged { get; set; }
    /// <summary>Page-size options shown in the rows-per-page selector.
    /// Empty array hides the selector entirely.</summary>
    [Parameter] public int[] PageSizeOptions { get; set; } = new[] { 10, 25, 50, 100 };
    [Parameter] public string? Class { get; set; }
    [Parameter(CaptureUnmatchedValues = true)] public Dictionary<string, object>? AdditionalAttributes { get; set; }

    private string CssClass => $"flex flex-wrap items-center gap-3 px-4 py-3 border-t border-border/40 {Class}".Trim();

    private int TotalPages => Context is not null && Context.PageSize > 0
        ? Math.Max(1, (int)Math.Ceiling((double)Context.TotalCount / Context.PageSize))
        : 1;

    private int StartItem => Context is not null && Context.TotalCount > 0
        ? (Context.CurrentPage - 1) * Context.PageSize + 1
        : 0;

    private int EndItem => Context is not null
        ? Math.Min(Context.CurrentPage * Context.PageSize, Context.TotalCount)
        : 0;

    private async Task GoToPage(int page)
    {
        await PageChanged.InvokeAsync(page);
    }

    private async Task GoToPrevious()
    {
        if (Context is not null && Context.CurrentPage > 1)
        {
            await PageChanged.InvokeAsync(Context.CurrentPage - 1);
        }
    }

    private async Task GoToNext()
    {
        if (Context is not null && Context.CurrentPage < TotalPages)
        {
            await PageChanged.InvokeAsync(Context.CurrentPage + 1);
        }
    }

    private async Task OnPageSizeSelected(string value)
    {
        if (int.TryParse(value, out var size))
        {
            await PageSizeChanged.InvokeAsync(size);
        }
    }

    private List<int> GetPageNumbers()
    {
        var pages = new List<int>();
        var total = TotalPages;
        var current = Context?.CurrentPage ?? 1;

        if (total <= 7)
        {
            for (var i = 1; i <= total; i++) pages.Add(i);
        }
        else
        {
            pages.Add(1);
            if (current > 3) pages.Add(-1); // ellipsis
            var start = Math.Max(2, current - 1);
            var end = Math.Min(total - 1, current + 1);
            for (var i = start; i <= end; i++) pages.Add(i);
            if (current < total - 2) pages.Add(-1); // ellipsis
            pages.Add(total);
        }

        return pages;
    }
}
