@* Reusable data table with sorting, filtering, and pagination *@
@typeparam TItem

<div class="mb-2">
    @if (ShowSearch)
    {
        <div class="row mb-2">
            <div class="col-md-4">
                <div class="input-group input-group-sm">
                    <input type="text" class="form-control form-control-sm" placeholder="Search..."
                           @bind="_searchTerm" @bind:event="oninput" @bind:after="ApplyFilter" />
                    @if (!string.IsNullOrEmpty(_searchTerm))
                    {
                        <button type="button" class="btn btn-outline-secondary"
                                aria-label="Clear search" @onclick="ClearSearch">&times;</button>
                    }
                </div>
            </div>
            @if (FilterContent != null)
            {
                <div class="col-md-8 d-flex gap-2 align-items-center">
                    @FilterContent
                </div>
            }
        </div>
    }
</div>

<table class="table table-sm table-striped table-hover">
    <thead class="table-dark">
        <tr>
            @HeaderContent
        </tr>
    </thead>
    <tbody>
        @if (_pagedItems.Count == 0)
        {
            <tr>
                <td colspan="100" class="text-muted text-center">@EmptyMessage</td>
            </tr>
        }
        else
        {
            @foreach (var item in _pagedItems)
            {
                @RowContent(item)
            }
        }
    </tbody>
</table>

@if (_totalPages > 1)
{
    <nav>
        <ul class="pagination pagination-sm justify-content-end">
            <li class="page-item @(_currentPage <= 1 ? "disabled" : "")">
                <button class="page-link" type="button"
                        disabled="@(_currentPage <= 1)"
                        aria-disabled="@((_currentPage <= 1).ToString().ToLowerInvariant())"
                        @onclick="() => GoToPage(_currentPage - 1)">Previous</button>
            </li>
            @for (int i = 1; i <= _totalPages; i++)
            {
                var page = i;
                <li class="page-item @(page == _currentPage ? "active" : "")">
                    <button class="page-link" @onclick="() => GoToPage(page)">@(page)</button>
                </li>
            }
            <li class="page-item @(_currentPage >= _totalPages ? "disabled" : "")">
                <button class="page-link" type="button"
                        disabled="@(_currentPage >= _totalPages)"
                        aria-disabled="@((_currentPage >= _totalPages).ToString().ToLowerInvariant())"
                        @onclick="() => GoToPage(_currentPage + 1)">Next</button>
            </li>
        </ul>
    </nav>
}

<div class="text-muted small">
    Showing @((_currentPage - 1) * PageSize + 1)&ndash;@Math.Min(_currentPage * PageSize, _filteredItems.Count) of @_filteredItems.Count items
</div>

@code {
    private string _searchTerm = string.Empty;
    private int _currentPage = 1;
    private List<TItem> _filteredItems = new();
    private List<TItem> _pagedItems = new();
    private int _totalPages;

    [Parameter, EditorRequired] public IReadOnlyList<TItem> Items { get; set; } = [];
    [Parameter, EditorRequired] public RenderFragment HeaderContent { get; set; } = default!;
    [Parameter, EditorRequired] public RenderFragment<TItem> RowContent { get; set; } = default!;
    [Parameter] public RenderFragment? FilterContent { get; set; }
    [Parameter] public int PageSize { get; set; } = 25;
    [Parameter] public bool ShowSearch { get; set; } = true;
    [Parameter] public string EmptyMessage { get; set; } = "No items found.";
    [Parameter] public Func<TItem, string, bool>? SearchFilter { get; set; }

    protected override void OnParametersSet()
    {
        ApplyFilter();
    }

    private void ApplyFilter()
    {
        if (!string.IsNullOrWhiteSpace(_searchTerm) && SearchFilter != null)
        {
            _filteredItems = Items.Where(i => SearchFilter(i, _searchTerm)).ToList();
        }
        else
        {
            _filteredItems = Items.ToList();
        }

        _totalPages = Math.Max(1, (int)Math.Ceiling(_filteredItems.Count / (double)PageSize));
        if (_currentPage > _totalPages) _currentPage = 1;

        UpdatePage();
    }

    private void GoToPage(int page)
    {
        if (page < 1 || page > _totalPages) return;
        _currentPage = page;
        UpdatePage();
    }

    private void ClearSearch()
    {
        _searchTerm = string.Empty;
        ApplyFilter();
    }

    private void UpdatePage()
    {
        _pagedItems = _filteredItems
            .Skip((_currentPage - 1) * PageSize)
            .Take(PageSize)
            .ToList();
    }

    public void Refresh()
    {
        ApplyFilter();
        StateHasChanged();
    }
}
