@page "/voiceworks"
@using JSMR.Application.Common.Search
@using JSMR.Application.VoiceWorks.Queries.Search
@using JSMR.UI.Blazor.Components
@using JSMR.UI.Blazor.Components.Authentication
@using JSMR.UI.Blazor.Enums
@using JSMR.UI.Blazor.Filters
@using JSMR.UI.Blazor.Services
@using JSMR.UI.Blazor.Shared
@using Microsoft.AspNetCore.WebUtilities
@inject VoiceWorksClient Client

@inherits SearchPageBase<VoiceWorkFilterState, VoiceWorkSearchResult>

<PageTitle>Voice Works</PageTitle>

<h3>Voice Works</h3>

<VoiceWorkFilters Value="@State" ValueChanged="UpdateAsync" />
<JProductCollection Products="Result?.Items"></JProductCollection>

@if (Result is not null)
{
    <JPagination PageNumber="@State.PageNumber"
                 PageNumberChanged="@(pageNumber => UpdateAsync(State with { PageNumber = pageNumber }))"
                 PageSize="@State.PageSize"
                 PageSizeChanged="@(pageSize => UpdateAsync(State with { PageSize = pageSize, PageNumber = 1 }))"
                 @bind-TotalItems="Result.TotalItems">
        <RightContent>
            <BitDropdown Items="sortOptions"
                         Style="min-width: 17rem"
                         Placeholder="Select..."
                         TItem="BitDropdownItem<VoiceWorkSort>"
                         TValue="VoiceWorkSort"
                         Value="@State.Sort"
                         ValueChanged="@(value => UpdateAsync(State with { Sort = value }))">
                <PrefixTemplate>
                    <InputPrefix Graphic="Graphic.Sort" Tooltip="Sort"></InputPrefix>
                </PrefixTemplate>
            </BitDropdown>
        </RightContent>
    </JPagination>
}

@code {
    [Inject]
    ILookupDataService Lookups { get; set; } = default!;

    List<BitDropdownItem<VoiceWorkSort>> sortOptions = [];

    protected override async Task OnInitializedAsync()
    {
        sortOptions = Lookups.GetSortOptions();

        await base.OnInitializedAsync();
    }

    protected override VoiceWorkFilterState ParseStateFromUri(string absoluteUri)
        => VoiceWorkFilterState.FromQuery(new Uri(absoluteUri).Query);

    protected override string BuildUri(VoiceWorkFilterState state)
    {
        var basePath = new Uri(Nav.Uri).GetLeftPart(UriPartial.Path);
        return Microsoft.AspNetCore.WebUtilities.QueryHelpers.AddQueryString(basePath, state.ToQuery());
    }

    protected override bool IsThisPage(string absoluteUri)
        => Nav.ToBaseRelativePath(absoluteUri).StartsWith("voiceworks", StringComparison.OrdinalIgnoreCase);

    protected override Task<SearchResult<VoiceWorkSearchResult>> ExecuteSearchAsync(VoiceWorkFilterState state, CancellationToken ct)
        => Client.SearchAsync(state.ToSearchRequest(), ct).ContinueWith(t => t.Result?.Results ?? new SearchResult<VoiceWorkSearchResult>(), ct);
}