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

namespace FrontOffice.Main.Pages.Network;

public partial class NetworkStatisticsPage : ComponentBase
{
    [Inject] private NetworkMembershipService NetworkService { get; set; } = default!;

    private NetworkStatisticsDto? _statistics;
    private bool _isLoading = true;
    private bool _hasError = false;

    private readonly ChartOptions _chartOptions = new()
    {
        ChartPalette = new[]
        {
            "#2196F3", // Info (Left)
            "#4CAF50"  // Success (Right)
        }
    };

    protected override async Task OnInitializedAsync()
    {
        await LoadStatisticsAsync();
    }

    private async Task LoadStatisticsAsync()
    {
        try
        {
            _isLoading = true;
            _hasError = false;
            _statistics = await NetworkService.GetMyNetworkStatisticsAsync();
        }
        catch (Exception ex)
        {
            _hasError = true;
            Snackbar.Add($"خطا در دریافت آمار: {ex.Message}", Severity.Error);
        }
        finally
        {
            _isLoading = false;
        }
    }

    private double GetLeftPercentage()
    {
        if (_statistics is null || _statistics.TotalMembers == 0)
            return 0;
        return (_statistics.LeftLegCount / (double)_statistics.TotalMembers) * 100;
    }

    private double GetRightPercentage()
    {
        if (_statistics is null || _statistics.TotalMembers == 0)
            return 0;
        return (_statistics.RightLegCount / (double)_statistics.TotalMembers) * 100;
    }

    private string GetLegText(string leg) => leg.ToLower() switch
    {
        "left" => "بخش (A)",
        "right" => "بخش (B)",
        _ => leg
    };

    private string GetPositionText(string position) => position.ToLower() switch
    {
        "left" => "(A)",
        "right" => "(B)",
        _ => position
    };

    private string GetInitials(string fullName)
    {
        if (string.IsNullOrWhiteSpace(fullName))
            return "؟";

        var parts = fullName.Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries);
        if (parts.Length >= 2)
            return $"{parts[0][0]}{parts[1][0]}";
        return fullName.Length > 0 ? fullName[0].ToString() : "؟";
    }
}
