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

namespace BackOffice.Pages.AutoComplete;

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

    [Parameter] public List<long> SelectedIds { get; set; } = new();
    [Parameter] public string? Label { get; set; } = "انتخاب دسته‌بندی‌ها";
    [Parameter] public EventCallback<List<long>> SelectedIdsChanged { get; set; }

    private List<GetAllCategoryByFilterResponseModel> _items = new();
    private HashSet<GetAllCategoryByFilterResponseModel> _selectedItems = new();

    protected override async Task OnParametersSetAsync()
    {
        await base.OnParametersSetAsync();

        if (SelectedIds == null || SelectedIds.Count == 0)
        {
            _selectedItems.Clear();
            return;
        }

        // اگر تعداد آیدی‌های فعلی با انتخاب‌ها برابر است، از لود مجدد صرفنظر می‌کنیم
        if (_selectedItems.Count == SelectedIds.Count &&
            _selectedItems.All(x => SelectedIds.Contains(x.Id)))
        {
            return;
        }

        _selectedItems.Clear();

        foreach (var id in SelectedIds.Distinct())
        {
            try
            {
                var response = await CategoryService.GetCategoryAsync(new GetCategoryRequest
                {
                    Id = id
                });

                if (response != null)
                {
                    _selectedItems.Add(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
                    });
                }
            }
            catch
            {
                // در صورت خطا، از ادامه برای آن آیدی صرفنظر می‌کنیم
            }
        }
    }

    private async Task OnSelectedValuesChanged(HashSet<GetAllCategoryByFilterResponseModel> values)
    {
        _selectedItems = values ?? new HashSet<GetAllCategoryByFilterResponseModel>();

        var ids = _selectedItems
            .Select(x => x.Id)
            .Distinct()
            .ToList();

        SelectedIds = ids;

        if (SelectedIdsChanged.HasDelegate)
        {
            await SelectedIdsChanged.InvokeAsync(ids);
        }
    }

    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 = 20
            }
        };

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

        return _items;
    }
}

