using Microsoft.AspNetCore.Components;
using MudBlazor;
using System.Globalization;
using CMSMicroservice.Protobuf.Protos.Commission;
using BackOffice.Services;

namespace BackOffice.Pages.Commission;

public partial class Dashboard
{
    [Inject] public CommissionContract.CommissionContractClient CommissionContract { get; set; }
    [Inject] public IPersianDateTimeService PersianDateTime { get; set; }
    [Inject] public NavigationManager NavigationManager { get; set; }


    [SupplyParameterFromQuery(Name = "weekId")]
    public long? WeekIdQueryParam { get; set; }

    private bool _isLoading = true;
    private long _currentWeekDefinitionId;
    private string _currentWeekDisplayName = string.Empty;
    private string _currentWeekDisplayText = string.Empty; // نمایش فارسی
    private GetWeeklyCommissionPoolResponse? _poolData;

    // Package filter
    private long? _selectedPackageId;

    // Available weeks data
    private CMSMicroservice.Protobuf.Protos.Commission.GetAvailableWeeksResponse? _availableWeeks;
    private List<CMSMicroservice.Protobuf.Protos.Commission.WeekInfo> _allWeeks = new();

    protected override async Task OnInitializedAsync()
    {
        // بارگذاری لیست هفته‌های قابل انتخاب
        await LoadAvailableWeeks();

        // اگر query string آمده، از آن استفاده کن
        if (WeekIdQueryParam.HasValue && WeekIdQueryParam.Value > 0)
        {
            _currentWeekDefinitionId = WeekIdQueryParam.Value;
            // پیدا کردن نام نمایشی از لیست هفته‌ها
            var weekInfo = _allWeeks.FirstOrDefault(w => w.WeekDefinitionId == _currentWeekDefinitionId);
            _currentWeekDisplayName = weekInfo?.DisplayName ?? "";
            _currentWeekDisplayText = weekInfo?.DisplayText ?? "";
        }
        else if (_availableWeeks?.CurrentWeek != null)
        {
            // استفاده از هفته جاری
            _currentWeekDefinitionId = _availableWeeks.CurrentWeek.WeekDefinitionId;
            _currentWeekDisplayName = _availableWeeks.CurrentWeek.DisplayName;
            _currentWeekDisplayText = _availableWeeks.CurrentWeek.DisplayText;
        }
        
        await LoadPoolData();
    }

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

            _availableWeeks = await CommissionContract.GetAvailableWeeksAsync(request);

            // ترکیب همه هفته‌ها برای dropdown
            _allWeeks.Clear();
            if (_availableWeeks.CurrentWeek != null)
                _allWeeks.Add(_availableWeeks.CurrentWeek);
            _allWeeks.AddRange(_availableWeeks.CalculatedWeeks);
            _allWeeks.AddRange(_availableWeeks.PendingWeeks);
            _allWeeks.AddRange(_availableWeeks.FutureWeeks);
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا در بارگذاری لیست هفته‌ها: {ex.Message}", Severity.Warning);
        }
    }

    private async Task OnWeekChanged(long weekDefinitionId)
    {
        _currentWeekDefinitionId = weekDefinitionId;
        var weekInfo = _allWeeks.FirstOrDefault(w => w.WeekDefinitionId == weekDefinitionId);
        _currentWeekDisplayName = weekInfo?.DisplayName ?? "";
        _currentWeekDisplayText = weekInfo?.DisplayText ?? "";
        
        // به‌روزرسانی URL با query string
        var uri = NavigationManager.GetUriWithQueryParameter("weekId", weekDefinitionId.ToString());
        NavigationManager.NavigateTo(uri, false);
        
        await LoadPoolData();
    }

    private async Task OnPackageChanged(long? packageId)
    {
        _selectedPackageId = packageId;
        await LoadPoolData();
    }

    private async Task LoadPoolData()
    {
        if (_currentWeekDefinitionId <= 0)
        {
            Snackbar.Add("هفته انتخاب نشده است", Severity.Warning);
            return;
        }
        
        try
        {
            _isLoading = true;
            StateHasChanged();

            var request = new GetWeeklyCommissionPoolRequest
            {
                WeekDefinitionId = _currentWeekDefinitionId,
                PackageId = _selectedPackageId
            };

            _poolData = await CommissionContract.GetWeeklyCommissionPoolAsync(request);
            Snackbar.Add($"اطلاعات Pool هفته {_currentWeekDisplayName} بارگذاری شد", Severity.Success);
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا در بارگذاری اطلاعات: {ex.Message}", Severity.Error);
            _poolData = null;
        }
        finally
        {
            _isLoading = false;
            StateHasChanged();
        }
    }

    private async Task TriggerCalculation()
    {
        var packageInfo = _selectedPackageId.HasValue 
            ? $" (فقط پکیج #{_selectedPackageId})" 
            : " (همه پکیج‌ها)";

        var confirmed = await DialogService.ShowMessageBox(
            "تایید",
            $"آیا از اجرای محاسبه دستی برای هفته {_currentWeekDisplayName}{packageInfo} مطمئن هستید؟",
            yesText: "بله", cancelText: "خیر");

        if (confirmed == true)
        {
            try
            {
                var req = new TriggerWeeklyCalculationRequest()
                {
                    WeekDefinitionId = _currentWeekDefinitionId,
                    ForceRecalculate = true,
                    SkipBalances = false,
                    SkipPayouts = false,
                    SkipPool = false,
                };

                req.PackageId = _selectedPackageId;

                var response = await CommissionContract.TriggerWeeklyCalculationAsync(req);

                if (response.Success)
                {
                    Snackbar.Add("محاسبه با موفقیت انجام شد.", Severity.Success);
                }
                else
                {
                    Snackbar.Add($"خطا در محاسبه: {response.Message}", Severity.Error);
                    return;
                }

                // Reload data after a delay
                await Task.Delay(2000);
                await LoadPoolData();
            }
            catch (Exception ex)
            {
                Snackbar.Add($"خطا در اجرای محاسبه: {ex.Message}", Severity.Error);
            }
        }
    }
}