@using Iceshrimp.Frontend.Core.Miscellaneous
@using Iceshrimp.Frontend.Core.Services
@using Iceshrimp.Shared.Schemas.Web
@* ReSharper disable once RedundantUsingDirective *@
@using Iceshrimp.Frontend.Components.Note
@inject ApiService                Api;
@inject ILogger<NoteQuoteDetails> Logger;
@inject NavigationManager         Nav;

@if (State is State.Loaded)
{
    <div class="quotes">
        @foreach (var el in Quotes)
        {
            <div class="quote">
                <Note NoteResponse="el" OpenNote="false"/>
            </div>
        }
        @if (EndReached is false)
        {
            <ScrollEnd ManualLoad="LoadMore" IntersectionChange="LoadMore"/>
        }
    </div>
}

@code {
    [Parameter, EditorRequired] public required string             NoteId     { get; set; }
    private                                     State              State      { get; set; }
    private                                     List<NoteResponse> Quotes     { get; set; } = [];
    private                                     PaginationData     Pd         { get; set; } = null!;
    private                                     bool               EndReached { get; set; } = false;

    protected override async Task OnInitializedAsync()
    {
        try
        {
            var res = await Api.Notes.GetQuotesAsync(NoteId, new PaginationQuery { Limit = 20 });
            if (res is null)
            {
                State = State.NotFound;
                Logger.LogWarning($"Quotes for '{NoteId}' not found.");
                return;
            }

            if (res.Links.Next is null) EndReached = true;
            Quotes = res.Data;
            Pd     = res.Links;
            State  = State.Loaded;
        }
        catch (ApiException e)
        {
            Logger.LogError(e, "Failed to load quotes");
            State = State.Error;
        }
    }

    private async Task<PaginationWrapper<List<NoteResponse>>?> FetchMore(PaginationData data)
    {
        if (data.Next is null) return null;
        var pq  = new PaginationQuery { MaxId = data.Next?.Split('=')[1], Limit = 20 };
        var res = await Api.Notes.GetQuotesAsync(NoteId, pq);
        return res;
    }

    private async Task LoadMore()
    {
        if (EndReached) return;
        try
        {
            var res = await FetchMore(Pd);
            if (res is null)
            {
                EndReached = true;
                return;
            }

            Pd = res.Links;
            Quotes.AddRange(res.Data);
        }
        catch (ApiException e)
        {
            Logger.LogError(e, "Failed to load Quotes");
        }
    }
}