    using CMSMicroservice.Protobuf.Protos.User;
using Grpc.Core;
using Microsoft.AspNetCore.Components;

namespace BackOffice.Pages.AutoComplete;

public partial class UserAutoComplete
{
    [Inject] public UserContract.UserContractClient UserContract { get; set; }
    
    [Parameter] public string Label { get; set; } = "انتخاب کاربر";
    [Parameter] public long? SelectedUserId { get; set; }
    [Parameter] public EventCallback<long?> SelectedUserIdChanged { get; set; }

    private GetAllUserByFilterResponseModel _item;

    protected override async Task OnParametersSetAsync()
    {
        if (SelectedUserId.HasValue && SelectedUserId.Value > 0 && _item?.Id != SelectedUserId.Value)
        {
            await LoadUser(SelectedUserId.Value);
        }
    }

    private async Task<IEnumerable<GetAllUserByFilterResponseModel>> Search(string value, CancellationToken cancellationToken)
    {
        if (string.IsNullOrWhiteSpace(value) || value.Length < 2)
            return new List<GetAllUserByFilterResponseModel>();

        try
        {
            var request = new GetAllUserByFilterRequest
            {
                PaginationState = new() { PageNumber = 1, PageSize = 100 },
                Filter = new() 
                { 
                   
                    SearchText = value,

                }
            };

            var response = await UserContract.GetAllUserByFilterAsync(request, cancellationToken: cancellationToken);
            return response.Models?.ToList() ?? new List<GetAllUserByFilterResponseModel>();
        }
        catch (RpcException ex) when (ex.StatusCode == StatusCode.Cancelled)
        {
            return new List<GetAllUserByFilterResponseModel>();
        }
        catch
        {
            return new List<GetAllUserByFilterResponseModel>();
        }
    }

    private async Task OnSelected(GetAllUserByFilterResponseModel selected)
    {
        _item = selected;
        var userId = selected?.Id;
        SelectedUserId = userId;
        await SelectedUserIdChanged.InvokeAsync(userId);
    }

    private async Task LoadUser(long userId)
    {
        try
        {
            var request = new GetAllUserByFilterRequest
            {
                PaginationState = new() { PageNumber = 1, PageSize = 1 },
                Filter = new()
                {
                    Id = userId
                }
            };
            
            var response = await UserContract.GetAllUserByFilterAsync(request);
            
            if (response.Models != null && response.Models.Count > 0)
            {
                _item = response.Models[0];
            }
        }
        catch
        {
            // Silent fail
        }
    }
}
