@* Merged into /club *@

@using MudBlazor
@using CMSMicroservice.Protobuf.Protos.ClubMembership

<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.CardMembership" 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">@_activeMembers.ToString("N0")</MudText>
                                <MudText Typo="Typo.caption" Color="Color.Success">@_activePercentage%</MudText>
                            </div>
                            <MudIcon Icon="@Icons.Material.Filled.CheckCircle" 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">@_inactiveMembers.ToString("N0")</MudText>
                                <MudText Typo="Typo.caption" Color="Color.Error">@_inactivePercentage%</MudText>
                            </div>
                            <MudIcon Icon="@Icons.Material.Filled.Cancel" Color="Color.Error" 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">@_averageDuration.ToString("F0")</MudText>
                                <MudText Typo="Typo.caption" Color="Color.Info">روز</MudText>
                            </div>
                            <MudIcon Icon="@Icons.Material.Filled.Timeline" Color="Color.Info" Size="Size.Large" />
                        </div>
                    </MudCardContent>
                </MudCard>
            </MudItem>
        </MudGrid>

        <!-- Charts -->
        <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="@_statusData" 
                                  InputLabels="@_statusLabels">
                        </MudChart>
                    </MudCardContent>
                </MudCard>
            </MudItem>
            <MudItem xs="12" md="6">
                <MudCard>
                    <MudCardHeader>
                        <MudText Typo="Typo.h6">روند عضویت‌ها (6 ماه اخیر)</MudText>
                    </MudCardHeader>
                    <MudCardContent>
                        <MudChart ChartType="ChartType.Line" 
                                  ChartSeries="@_membershipTrend" 
                                  XAxisLabels="@_trendLabels" 
                                  Width="100%"
                                  Height="300px">
                        </MudChart>
                    </MudCardContent>
                </MudCard>
            </MudItem>
        </MudGrid>

        <!-- Package Distribution -->
        <MudCard Class="mb-4">
            <MudCardHeader>
                <MudText Typo="Typo.h6">توزیع پکیج‌ها</MudText>
            </MudCardHeader>
            <MudCardContent>
                <MudChart ChartType="ChartType.Bar" 
                          ChartSeries="@_packageSeries" 
                          XAxisLabels="@_packageLabels"
                          Width="100%"
                          Height="300px">
                </MudChart>
            </MudCardContent>
        </MudCard>

        <!-- Recent Memberships -->
        <MudCard>
            <MudCardHeader>
                <MudText Typo="Typo.h6">عضویت‌های اخیر (30 روز گذشته)</MudText>
            </MudCardHeader>
            <MudCardContent>
                <MudTable T="RecentMembershipModel" Items="@_recentMemberships" Hover="true" Dense="true">
                    <HeaderContent>
                        <MudTh>تاریخ</MudTh>
                        <MudTh>شناسه کاربر</MudTh>
                        <MudTh>نام کاربر</MudTh>
                        <MudTh>پکیج</MudTh>
                        <MudTh>وضعیت</MudTh>
                        <MudTh>عملیات</MudTh>
                    </HeaderContent>
                    <RowTemplate>
                        <MudTd DataLabel="تاریخ">@context.ActivatedAt.MiladiToJalali()</MudTd>
                        <MudTd DataLabel="شناسه کاربر">@context.UserId</MudTd>
                        <MudTd DataLabel="نام کاربر">@context.UserName</MudTd>
                        <MudTd DataLabel="پکیج">
                            <MudChip T="string" Color="Color.Primary" Size="Size.Small">@context.PackageName</MudChip>
                        </MudTd>
                        <MudTd DataLabel="وضعیت">
                            <MudChip T="string" 
                                     Color="@(context.IsActive ? Color.Success : Color.Error)" 
                                     Size="Size.Small">
                                @(context.IsActive ? "فعال" : "غیرفعال")
                            </MudChip>
                        </MudTd>
                        <MudTd DataLabel="عملیات">
                            <MudButton Size="Size.Small" 
                                       Variant="Variant.Text" 
                                       Color="Color.Primary"
                                       StartIcon="@Icons.Material.Filled.Visibility"
                                       Href="/club/members">
                                مشاهده
                            </MudButton>
                        </MudTd>
                    </RowTemplate>
                </MudTable>
            </MudCardContent>
        </MudCard>
    }
</div>

@code {
    [Inject] public ClubMembershipContract.ClubMembershipContractClient ClubClient { get; set; }

    private bool _loading = false;
    
    // Statistics
    private int _totalMembers = 0;
    private int _activeMembers = 0;
    private int _inactiveMembers = 0;
    private int _activePercentage = 0;
    private int _inactivePercentage = 0;
    private double _averageDuration = 0;

    // Chart data
    private double[] _statusData = Array.Empty<double>();
    private string[] _statusLabels = Array.Empty<string>();
    private List<ChartSeries> _membershipTrend = new();
    private string[] _trendLabels = Array.Empty<string>();
    private List<ChartSeries> _packageSeries = new();
    private string[] _packageLabels = Array.Empty<string>();
    
    private List<RecentMembershipModel> _recentMemberships = new();

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

    private async Task LoadStatistics()
    {
        _loading = true;
        try
        {
            var response = await ClubClient.GetClubStatisticsAsync(new GetClubStatisticsRequest());
            
            // Basic stats
            _totalMembers = response.TotalMembers;
            _activeMembers = response.ActiveMembers;
            _inactiveMembers = response.InactiveMembers;
            _activePercentage = (int)response.ActivePercentage;
            _inactivePercentage = 100 - _activePercentage;
            _averageDuration = response.AverageMembershipDurationDays;

            // Status distribution
            _statusData = new double[] { _activeMembers, _inactiveMembers };
            _statusLabels = new[] { "فعال", "غیرفعال" };

            // Membership trend
            _trendLabels = response.MonthlyTrend.Select(t => t.Month).ToArray();
            _membershipTrend = new List<ChartSeries>
            {
                new ChartSeries 
                { 
                    Name = "عضویت‌های جدید", 
                    Data = response.MonthlyTrend.Select(t => (double)t.Activations).ToArray() 
                },
                new ChartSeries 
                { 
                    Name = "لغو عضویت", 
                    Data = response.MonthlyTrend.Select(t => (double)t.Expirations).ToArray() 
                }
            };

            // Package distribution from response
            _packageLabels = response.PackageDistribution.Select(p => p.PackageName).ToArray();
            _packageSeries = new List<ChartSeries>
            {
                new ChartSeries 
                { 
                    Name = "تعداد اعضا", 
                    Data = response.PackageDistribution.Select(p => (double)p.MemberCount).ToArray() 
                }
            };

            // Recent memberships - would need a separate API call to get individual records
            // For now, keep empty or remove this section
            _recentMemberships = new List<RecentMembershipModel>();
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا در بارگذاری آمار: {ex.Message}", Severity.Error);
        }
        finally
        {
            _loading = false;
        }
    }



    private class RecentMembershipModel
    {
        public DateTime ActivatedAt { get; set; }
        public long UserId { get; set; }
        public string UserName { get; set; }
        public string PackageName { get; set; }
        public bool IsActive { get; set; }
    }
}
