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

namespace BackOffice.Pages.AutoComplete;

public partial class CategoryAutoComplete
{
    [Inject] public CategoryContract.CategoryContractClient CategoryService { get; set; } = default!;

    [Parameter] public long? Value { get; set; }
    [Parameter] public string? Label { get; set; } = "دسته‌بندی والد";
    [Parameter] public EventCallback<long?> ValueChanged { get; set; }

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

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

        if (Value.HasValue && Value.Value > 0)
        {
            var response = await CategoryService.GetCategoryAsync(new GetCategoryRequest
            {
                Id = Value.Value
            });

            if (response != null)
            {
                _item = new GetAllCategoryByFilterResponseModel
                {
                    Id = response.Id,
                    Name = response.Name,
                    Title = response.Title,
                    Description = response.Description,
                    ImagePath = response.ImagePath,
                    ParentId = response.ParentId,
                    IsActive = response.IsActive,
                    SortOrder = response.SortOrder
                };

                StateHasChanged();
            }
        }
    }

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

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

        var response = await CategoryService.GetAllCategoryByFilterAsync(request, cancellationToken: token);
        _items = response?.Models?.ToList() ?? new List<GetAllCategoryByFilterResponseModel>();

        return _items;
    }
}

