using BackOffice.Services;
using CMSMicroservice.Protobuf.Protos.Commission;
using Grpc.Core;
using Microsoft.AspNetCore.Components;

namespace BackOffice.Pages.AutoComplete;

public partial class WeekNumberPicker
{
    [Inject] public CommissionContract.CommissionContractClient CommissionContract { get; set; } = default!;
    [Inject] public IPersianDateTimeService PersianDateTime { get; set; } = default!;
    
    [Parameter] public string Label { get; set; } = "انتخاب هفته";
    
    // WeekDefinitionId based binding (preferred)
    [Parameter] public long? SelectedWeekDefinitionId { get; set; }
    [Parameter] public EventCallback<long?> SelectedWeekDefinitionIdChanged { get; set; }
    
    // Legacy string-based binding (deprecated, kept for compatibility)
    // [Parameter] public long? SelectedWeekNumber { get; set; }
    // [Parameter] public EventCallback<long?> SelectedWeekNumberChanged { get; set; }
    
    [Parameter] public bool CoerceText { get; set; } = true; // اجازه ورود دستی
    [Parameter] public int FutureWeeksCount { get; set; } = 4;
    [Parameter] public int PastWeeksCount { get; set; } = 12;

    private WeekInfo? _selectedWeek;
    private List<WeekInfo> _allWeeks = new();
    private bool _isLoaded = false;

    protected override async Task OnInitializedAsync()
    {
        await LoadWeeks();
        
        if (SelectedWeekDefinitionId.HasValue && SelectedWeekDefinitionId.Value > 0 && _allWeeks.Any())
        {
            _selectedWeek = _allWeeks.FirstOrDefault(w => w.WeekDefinitionId == SelectedWeekDefinitionId.Value);
        }
        // else if (SelectedWeekNumber!=null && SelectedWeekNumber>0 && _allWeeks.Any())
        // {
        //     _selectedWeek = _allWeeks.FirstOrDefault(w => w.WeekDefinitionId == SelectedWeekNumber);
        // }
    }

    protected override async Task OnParametersSetAsync()
    {
        if (SelectedWeekDefinitionId.HasValue && SelectedWeekDefinitionId.Value > 0 &&
            _selectedWeek?.WeekDefinitionId != SelectedWeekDefinitionId.Value && 
            _isLoaded)
        {
            _selectedWeek = _allWeeks.FirstOrDefault(w => w.WeekDefinitionId == SelectedWeekDefinitionId.Value);
        }
        // else if (SelectedWeekNumber!=null && SelectedWeekNumber>0  && 
        //          _selectedWeek?.WeekDefinitionId != SelectedWeekNumber && 
        //          _isLoaded)
        // {
        //     _selectedWeek = _allWeeks.FirstOrDefault(w => w.WeekDefinitionId == SelectedWeekNumber);
        // }
    }

    private async Task LoadWeeks()
    {
        try
        {
            var request = new GetAvailableWeeksRequest
            {
                FutureWeeksCount = FutureWeeksCount,
                PastWeeksCount = PastWeeksCount
            };

            var response = await CommissionContract.GetAvailableWeeksAsync(request);
            
            _allWeeks = new List<WeekInfo>();
            
            // ترتیب: هفته جاری، محاسبه شده، در انتظار، آینده
            if (response.CurrentWeek != null)
                _allWeeks.Add(response.CurrentWeek);
            
            if (response.CalculatedWeeks != null)
                _allWeeks.AddRange(response.CalculatedWeeks);
            
            if (response.PendingWeeks != null)
                _allWeeks.AddRange(response.PendingWeeks);
            
            if (response.FutureWeeks != null)
                _allWeeks.AddRange(response.FutureWeeks);

            _isLoaded = true;
        }
        catch
        {
            _allWeeks = new List<WeekInfo>();
            _isLoaded = true;
        }
    }

    private async Task<IEnumerable<WeekInfo>> Search(string value, CancellationToken cancellationToken)
    {
        if (!_isLoaded)
            await LoadWeeks();

        if (string.IsNullOrWhiteSpace(value))
            return _allWeeks;

        // جستجو در DisplayName یا DisplayText
        return _allWeeks
            .Where(w => w.DisplayName.Contains(value, StringComparison.OrdinalIgnoreCase) ||
                       w.DisplayText.Contains(value, StringComparison.OrdinalIgnoreCase))
            .ToList();
    }

    private async Task OnSelected(WeekInfo? selected)
    {
        _selectedWeek = selected;
        SelectedWeekDefinitionId = selected?.WeekDefinitionId;
        // SelectedWeekNumber = selected.WeekDefinitionId;
        await SelectedWeekDefinitionIdChanged.InvokeAsync(SelectedWeekDefinitionId);
        // await SelectedWeekNumberChanged.InvokeAsync(SelectedWeekNumber);
    }

    private async Task OnClear()
    {
        _selectedWeek = null;
        SelectedWeekDefinitionId = null;
        // SelectedWeekNumber = null;
        await SelectedWeekDefinitionIdChanged.InvokeAsync(null);
        // await SelectedWeekNumberChanged.InvokeAsync(null);
    }
}
