using CMSMicroservice.Protobuf.Protos.Package;
using Microsoft.AspNetCore.Components;

namespace BackOffice.Pages.AutoComplete;

public partial class PackageSelect
{
    [Inject] public PackageContract.PackageContractClient PackageClient { get; set; }

    [Parameter] public string Label { get; set; } = "پکیج";
    [Parameter] public long? SelectedPackageId { get; set; }
    [Parameter] public EventCallback<long?> SelectedPackageIdChanged { get; set; }

    private List<GetAllPackageByFilterResponseModel> _packages = new();

    protected override async Task OnInitializedAsync()
    {
        await LoadPackages();
    }

    private async Task LoadPackages()
    {
        try
        {
            var request = new GetAllPackageByFilterRequest
            {
                PaginationState = new() { PageNumber = 1, PageSize = 100 },
                Filter = new()
            };

            var result = await PackageClient.GetAllPackageByFilterAsync(request);
            _packages = result.Models?.OrderBy(p => p.SortOrder).ToList() 
                        ?? new List<GetAllPackageByFilterResponseModel>();
        }
        catch
        {
            _packages = new List<GetAllPackageByFilterResponseModel>();
        }
    }

    private async Task OnValueChanged(long? value)
    {
        SelectedPackageId = value;
        await SelectedPackageIdChanged.InvokeAsync(value);
    }
}
