@page "/network/statistics"

@using CMSMicroservice.Protobuf.Protos.NetworkMembership
@using MudBlazor

<div>
    <MudText Typo="Typo.h4" GutterBottom="true">آمار شبکه</MudText>
    <MudText Typo="Typo.body1" Color="Color.Secondary" Class="mb-4">
        نمای کلی از وضعیت شبکه و آمار اعضا
    </MudText>

    @if (_loading)
    {
        <MudProgressCircular Color="Color.Primary" Indeterminate="true" />
    }
    else
    {
        <!-- Summary Cards -->
        <MudGrid Class="mb-4">
            <MudItem xs="12" md="3">
                <MudCard Elevation="2">
                    <MudCardContent>
                        <div class="d-flex justify-space-between align-center">
                            <div>
                                <MudText Typo="Typo.body2" Color="Color.Secondary">کل اعضا</MudText>
                                <MudText Typo="Typo.h4">@_totalMembers.ToString("N0")</MudText>
                            </div>
                            <MudIcon Icon="@Icons.Material.Filled.People" Color="Color.Primary" Size="Size.Large" />
                        </div>
                    </MudCardContent>
                </MudCard>
            </MudItem>
            <MudItem xs="12" md="3">
                <MudCard Elevation="2">
                    <MudCardContent>
                        <div class="d-flex justify-space-between align-center">
                            <div>
                                <MudText Typo="Typo.body2" Color="Color.Secondary">شاخه چپ</MudText>
                                <MudText Typo="Typo.h4">@_leftCount.ToString("N0")</MudText>
                                <MudText Typo="Typo.caption" Color="Color.Success">@_leftPercentage%</MudText>
                            </div>
                            <MudIcon Icon="@Icons.Material.Filled.TrendingUp" Color="Color.Success" Size="Size.Large" />
                        </div>
                    </MudCardContent>
                </MudCard>
            </MudItem>
            <MudItem xs="12" md="3">
                <MudCard Elevation="2">
                    <MudCardContent>
                        <div class="d-flex justify-space-between align-center">
                            <div>
                                <MudText Typo="Typo.body2" Color="Color.Secondary">شاخه راست</MudText>
                                <MudText Typo="Typo.h4">@_rightCount.ToString("N0")</MudText>
                                <MudText Typo="Typo.caption" Color="Color.Warning">@_rightPercentage%</MudText>
                            </div>
                            <MudIcon Icon="@Icons.Material.Filled.TrendingDown" Color="Color.Warning" Size="Size.Large" />
                        </div>
                    </MudCardContent>
                </MudCard>
            </MudItem>
            <MudItem xs="12" md="3">
                <MudCard Elevation="2">
                    <MudCardContent>
                        <div class="d-flex justify-space-between align-center">
                            <div>
                                <MudText Typo="Typo.body2" Color="Color.Secondary">میانگین عمق</MudText>
                                <MudText Typo="Typo.h4">@_averageDepth.ToString("F1")</MudText>
                                <MudText Typo="Typo.caption" Color="Color.Info">سطح</MudText>
                            </div>
                            <MudIcon Icon="@Icons.Material.Filled.Height" Color="Color.Info" Size="Size.Large" />
                        </div>
                    </MudCardContent>
                </MudCard>
            </MudItem>
        </MudGrid>

        <!-- Distribution Chart -->
        <MudGrid Class="mb-4">
            <MudItem xs="12" md="6">
                <MudCard>
                    <MudCardHeader>
                        <MudText Typo="Typo.h6">توزیع شاخه‌ها</MudText>
                    </MudCardHeader>
                    <MudCardContent>
                        <MudChart ChartType="ChartType.Donut" 
                                  Width="300px" 
                                  Height="300px"
                                  InputData="@_distributionData" 
                                  InputLabels="@_distributionLabels">
                        </MudChart>
                    </MudCardContent>
                </MudCard>
            </MudItem>
            <MudItem xs="12" md="6">
                <MudCard>
                    <MudCardHeader>
                        <MudText Typo="Typo.h6">رشد ماهانه</MudText>
                    </MudCardHeader>
                    <MudCardContent>
                        <MudChart ChartType="ChartType.Line" 
                                  ChartSeries="@_growthSeries" 
                                  XAxisLabels="@_growthLabels" 
                                  Width="100%"
                                  Height="300px">
                        </MudChart>
                    </MudCardContent>
                </MudCard>
            </MudItem>
        </MudGrid>

        <!-- Depth Distribution -->
        <MudCard Class="mb-4">
            <MudCardHeader>
                <MudText Typo="Typo.h6">توزیع عمق شبکه</MudText>
            </MudCardHeader>
            <MudCardContent>
                <MudChart ChartType="ChartType.Bar" 
                          ChartSeries="@_depthSeries" 
                          XAxisLabels="@_depthLabels"
                          Width="100%"
                          Height="300px">
                </MudChart>
            </MudCardContent>
        </MudCard>

        <!-- Top 10 Users -->
        <MudCard>
            <MudCardHeader>
                <MudText Typo="Typo.h6">10 کاربر برتر (بیشترین زیرمجموعه)</MudText>
            </MudCardHeader>
            <MudCardContent>
                <MudTable T="TopUserModel" Items="@_topUsers" Hover="true" Dense="true">
                    <HeaderContent>
                        <MudTh>رتبه</MudTh>
                        <MudTh>شناسه کاربر</MudTh>
                        <MudTh>نام کاربر</MudTh>
                        <MudTh>تعداد زیرمجموعه</MudTh>
                        <MudTh>شاخه چپ</MudTh>
                        <MudTh>شاخه راست</MudTh>
                        <MudTh>عملیات</MudTh>
                    </HeaderContent>
                    <RowTemplate>
                        <MudTd DataLabel="رتبه">
                            <MudChip T="string" Color="@GetRankColor(context.Rank)" Size="Size.Small">@context.Rank</MudChip>
                        </MudTd>
                        <MudTd DataLabel="شناسه کاربر">@context.UserId</MudTd>
                        <MudTd DataLabel="نام کاربر">@context.UserName</MudTd>
                        <MudTd DataLabel="تعداد زیرمجموعه">@context.TotalChildren.ToString("N0")</MudTd>
                        <MudTd DataLabel="شاخه چپ">@context.LeftCount.ToString("N0")</MudTd>
                        <MudTd DataLabel="شاخه راست">@context.RightCount.ToString("N0")</MudTd>
                        <MudTd DataLabel="عملیات">
                            <MudButton Size="Size.Small" 
                                       Variant="Variant.Text" 
                                       Color="Color.Primary"
                                       StartIcon="@Icons.Material.Filled.Visibility"
                                       Href="@($"/network/user-info/{context.UserId}")">
                                مشاهده
                            </MudButton>
                        </MudTd>
                    </RowTemplate>
                </MudTable>
            </MudCardContent>
        </MudCard>
    }
</div>

@code {
    [Inject] public NetworkMembershipContract.NetworkMembershipContractClient NetworkClient { get; set; }

    private bool _loading = false;
    
    // Statistics
    private int _totalMembers = 0;
    private int _leftCount = 0;
    private int _rightCount = 0;
    private int _leftPercentage = 0;
    private int _rightPercentage = 0;
    private double _averageDepth = 0;

    // Chart data
    private double[] _distributionData = Array.Empty<double>();
    private string[] _distributionLabels = Array.Empty<string>();
    private List<ChartSeries> _growthSeries = new();
    private string[] _growthLabels = Array.Empty<string>();
    private List<ChartSeries> _depthSeries = new();
    private string[] _depthLabels = Array.Empty<string>();
    
    private List<TopUserModel> _topUsers = new();

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

    private async Task LoadStatistics()
    {
        _loading = true;
        try
        {
            var response = await NetworkClient.GetNetworkStatisticsAsync(new GetNetworkStatisticsRequest());
            
            // Basic stats
            _totalMembers = response.TotalMembers;
            _leftCount = response.LeftLegCount;
            _rightCount = response.RightLegCount;
            _leftPercentage = (int)response.LeftPercentage;
            _rightPercentage = (int)response.RightPercentage;
            _averageDepth = response.AverageDepth;

            // Distribution chart
            _distributionData = new double[] { _leftCount, _rightCount };
            _distributionLabels = new[] { "شاخه چپ", "شاخه راست" };

            // Growth chart
            _growthLabels = response.MonthlyGrowth.Select(m => m.Month).ToArray();
            _growthSeries = new List<ChartSeries>
            {
                new ChartSeries 
                { 
                    Name = "اعضای جدید", 
                    Data = response.MonthlyGrowth.Select(m => (double)m.NewMembers).ToArray() 
                }
            };

            // Depth distribution
            _depthLabels = response.LevelDistribution.Select(l => $"سطح {l.Level}").ToArray();
            _depthSeries = new List<ChartSeries>
            {
                new ChartSeries 
                { 
                    Name = "تعداد اعضا", 
                    Data = response.LevelDistribution.Select(l => (double)l.Count).ToArray() 
                }
            };

            // Top users
            _topUsers = response.TopUsers.Select(u => new TopUserModel
            {
                Rank = u.Rank,
                UserId = u.UserId,
                UserName = u.UserName,
                TotalChildren = u.TotalChildren,
                LeftCount = u.LeftCount,
                RightCount = u.RightCount
            }).ToList();
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا در بارگذاری آمار: {ex.Message}", Severity.Error);
        }
        finally
        {
            _loading = false;
        }
    }



    private Color GetRankColor(int rank)
    {
        return rank switch
        {
            1 => Color.Warning,
            2 => Color.Default,
            3 => Color.Tertiary,
            _ => Color.Primary
        };
    }

    private class TopUserModel
    {
        public int Rank { get; set; }
        public long UserId { get; set; }
        public string UserName { get; set; }
        public int TotalChildren { get; set; }
        public int LeftCount { get; set; }
        public int RightCount { get; set; }
    }
}
