using FrontOffice.Main.Shared;
using FrontOffice.Main.Utilities;
using Microsoft.AspNetCore.Components;
using MudBlazor;

namespace FrontOffice.Main.Pages.Commission;

public partial class CommissionDashboardPage : ComponentBase
{
    [Inject] private CommissionService CommissionService { get; set; } = default!;
    [Inject] private PackageService PackageService { get; set; } = default!;

    private List<CommissionPayoutDto> _payouts = new();
    private List<PackageDto> _packages = new();
    private int _totalCount;
    private long _totalAmount;
    private int _pageNumber = 1;
    private int _pageSize = 10;
    private bool _isLoading = true;

    private WeekSelector? _weekSelector;
    private WeekDefinitionDto? _selectedWeekDefinition;
    private string _filterStatus = string.Empty;
    private long? _filterPackageId;

    protected override async Task OnInitializedAsync()
    {
        await LoadPackagesAsync();
        await LoadPayoutsAsync();
    }

    private async Task LoadPackagesAsync()
    {
        try
        {
            _packages = await PackageService.GetAllPackagesAsync();
        }
        catch
        {
            _packages = new List<PackageDto>();
        }
    }

    private async Task LoadPayoutsAsync()
    {
        try
        {
            _isLoading = true;
            var weekDefinitionId = _selectedWeekDefinition?.Id;
            var result = await CommissionService.GetMyCommissionPayoutsAsync(
                weekDefinitionId,
                _filterStatus,
                _pageNumber,
                _pageSize,
                _filterPackageId
            );
            _payouts = result.Payouts;
            _totalCount = result.TotalCount;
            _totalAmount = _payouts.Sum(p => p.TotalAmount);
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا در دریافت پاداش‌ها: {ex.Message}", Severity.Error);
        }
        finally
        {
            _isLoading = false;
        }
    }

    private async Task ApplyFiltersAsync()
    {
        _pageNumber = 1;
        await LoadPayoutsAsync();
    }

    private async Task ClearFiltersAsync()
    {
        _selectedWeekDefinition = null;
        _filterStatus = string.Empty;
        _filterPackageId = null;
        _pageNumber = 1;
        await LoadPayoutsAsync();
    }

    private async Task OnPageChangedAsync(int page)
    {
        _pageNumber = page;
        await LoadPayoutsAsync();
    }

    private int GetTotalPages()
    {
        if (_totalCount == 0 || _pageSize == 0)
            return 1;
        return (int)Math.Ceiling(_totalCount / (double)_pageSize);
    }

    private string GetTotalEarnings()
    {
        return $"{_totalAmount:N0} تومان";
    }

    private string GetAverageWeekly()
    {
        if (_totalCount == 0)
            return "0 تومان";
        var avg = _totalAmount / _totalCount;
        return $"{avg:N0} تومان";
    }

    private Color GetStatusColor(string statusColor) => statusColor.ToLower() switch
    {
        "success" => Color.Success,
        "warning" => Color.Warning,
        "error" => Color.Error,
        "info" => Color.Info,
        _ => Color.Default
    };
}
