using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CMSMicroservice.Protobuf.Protos;
using CMSMicroservice.Protobuf.Protos.Category;
using Microsoft.AspNetCore.Components;

namespace BackOffice.Pages.AutoComplete;

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

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

    private List<GetAllCategoryByFilterResponseModel> _items = new();
    private HashSet<long> _internalSelectedIds = new();
    private MudBlazor.MudSelect<long>? _selectRef;

    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();
        await LoadCategoriesAsync();
        SyncInternalFromParameter();
    }

    protected override Task OnParametersSetAsync()
    {
        SyncInternalFromParameter();
        return base.OnParametersSetAsync();
    }

    private async Task LoadCategoriesAsync()
    {
        try
        {
            var response = await CategoryService.GetAllCategoryByFilterAsync(new GetAllCategoryByFilterRequest
            {
                Filter = new GetAllCategoryByFilterFilter(),
                PaginationState = new PaginationState
                {
                    PageNumber = 1,
                    PageSize = 1000
                }
            });

            _items = response?.Models?.ToList() ?? new List<GetAllCategoryByFilterResponseModel>();
        }
        catch
        {
            _items = new List<GetAllCategoryByFilterResponseModel>();
        }
    }

    private void SyncInternalFromParameter()
    {
        _internalSelectedIds = SelectedIds != null
            ? SelectedIds.Where(id => id > 0).Distinct().ToHashSet()
            : new HashSet<long>();
    }

    private async Task OnSelectedValuesChangedAsync(IEnumerable<long> values)
    {
        _internalSelectedIds = values.Where(id => id > 0).Distinct().ToHashSet();
        SelectedIds = _internalSelectedIds.ToList();

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

    private string GetSelectedText(List<string> selectedValues)
    {
        if (selectedValues == null || selectedValues.Count == 0)
            return string.Empty;

        var titles = new List<string>();
        foreach (var val in selectedValues)
        {
            if (long.TryParse(val, out var id))
            {
                var item = _items.FirstOrDefault(x => x.Id == id);
                titles.Add(item != null ? item.Title : val);
            }
            else
            {
                titles.Add(val);
            }
        }

        return string.Join("، ", titles);
    }
}

