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

namespace BackOffice.Pages.AutoComplete;

public partial class ProductsAutoComplete
{
    [Inject] public ProductsContract.ProductsContractClient ProductsService { get; set; } = default!;

    [Parameter] public long? Value { get; set; }
    [Parameter] public string? Label { get; set; } = "محصول";
    [Parameter] public EventCallback<long?> ValueChanged { get; set; }

    private List<GetAllProductsByFilterResponseModel> _items = new();
    private GetAllProductsByFilterResponseModel? _item;

    protected override async void OnParametersSet()
    {
        await base.OnParametersSetAsync();

        if (Value.HasValue && Value.Value > 0)
        {
            var getAll = await ProductsService.GetAllProductsByFilterAsync(new GetAllProductsByFilterRequest
            {
                Filter = new GetAllProductsByFilterFilter
                {
                    Id = Value.Value
                },
                PaginationState = new PaginationState
                {
                    PageNumber = 1,
                    PageSize = 1
                }
            });

            if (getAll?.Models != null && getAll.Models.Any())
            {
                _item = getAll.Models.First();
                StateHasChanged();
            }
        }
    }

    private async Task OnSelected(GetAllProductsByFilterResponseModel? model)
    {
        if (model == null)
        {
            _item = null;
            await ValueChanged.InvokeAsync(null);
        }
        else
        {
            _item = model;
            await ValueChanged.InvokeAsync(model.Id);
        }
    }

    private async Task<IEnumerable<GetAllProductsByFilterResponseModel>> Search(string value, CancellationToken token)
    {
        var request = new GetAllProductsByFilterRequest
        {
            Filter = new GetAllProductsByFilterFilter
            {
                Title = string.IsNullOrWhiteSpace(value) ? null : value
            },
            PaginationState = new PaginationState
            {
                PageNumber = 1,
                PageSize = 9
            }
        };

        var getAll = await ProductsService.GetAllProductsByFilterAsync(request);
        _items = getAll?.Models?.ToList() ?? new List<GetAllProductsByFilterResponseModel>();

        return _items;
    }
}

