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

namespace BackOffice.Pages.AutoComplete;

public partial class DiscountProductsAutoComplete
{
    [Inject] public DiscountProductContract.DiscountProductContractClient DiscountProductService { get; set; } = default!;

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

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

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

        if (Value.HasValue && Value.Value > 0 && (_item == null || _item.Id != Value.Value))
        {
            try
            {
                var getAll = await DiscountProductService.GetDiscountProductsAsync(new GetDiscountProductsRequest
                {
                    PageNumber = 1,
                    PageSize = 50
                });

                if (getAll?.Models != null)
                {
                    _item = getAll.Models.FirstOrDefault(x => x.Id == Value.Value);
                    StateHasChanged();
                }
            }
            catch
            {
                // Silently handle
            }
        }
    }

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

    private async Task<IEnumerable<DiscountProductDto>> Search(string value, CancellationToken token)
    {
        var request = new GetDiscountProductsRequest
        {
            PageNumber = 1,
            PageSize = 9
        };

        if (!string.IsNullOrWhiteSpace(value))
        {
            request.SearchQuery = value;
        }

        try
        {
            var getAll = await DiscountProductService.GetDiscountProductsAsync(request);
            _items = getAll?.Models?.ToList() ?? new List<DiscountProductDto>();
        }
        catch
        {
            _items = new List<DiscountProductDto>();
        }

        return _items;
    }
}
