@page "/network/balances"

@using BackOffice.Pages.AutoComplete
@using MudBlazor
@using CMSMicroservice.Protobuf.Protos.Commission

<div>
    <MudText Typo="Typo.h4" GutterBottom="true">گزارش موجودی‌های هفتگی</MudText>
    <MudText Typo="Typo.body1" Color="Color.Secondary" Class="mb-4">
        مشاهده موجودی‌های شبکه کاربران به تفکیک هفته
    </MudText>

    <MudCard Class="mb-4">
        <MudCardContent>
            <MudGrid>
                <MudItem xs="12" md="3">
                    @* <MudNumericField @bind-Value="_filterUserId"  *@
                    @*                  Label="شناسه کاربر"  *@
                    @*                  Variant="Variant.Outlined" *@
                    @*                  Min="0" /> *@
                    <UserAutoComplete Label="جستجوی کاربر" 
                                      @bind-SelectedUserId="_filterUserId" />
                </MudItem>
                <MudItem xs="12" md="3">
                    <WeekNumberPicker Label="شماره هفته" 
                                     @bind-SelectedWeekDefinitionId="_filterWeekDefinitionId"
                                     CoerceText="true" />
                </MudItem>
                <MudItem xs="12" md="2">
                    <MudNumericField @bind-Value="_minBalance" 
                                     Label="حداقل موجودی" 
                                     Variant="Variant.Outlined"
                                     Min="0" />
                </MudItem>
                <MudItem xs="12" md="2">
                    <MudNumericField @bind-Value="_maxBalance" 
                                     Label="حداکثر موجودی" 
                                     Variant="Variant.Outlined"
                                     Min="0" />
                </MudItem>
                <MudItem xs="12" md="2" Class="d-flex align-center">
                    <MudButton Variant="Variant.Filled" 
                               Color="Color.Primary" 
                               OnClick="ApplyFilter"
                               StartIcon="@Icons.Material.Filled.Search"
                               FullWidth="true">
                        جستجو
                    </MudButton>
                </MudItem>
            </MudGrid>
        </MudCardContent>
    </MudCard>

    <MudCard>
        <MudCardContent>
            <div class="d-flex justify-space-between align-center mb-3">
                <MudText Typo="Typo.h6">موجودی‌های هفتگی</MudText>
                <MudButton Variant="Variant.Filled" 
                           Color="Color.Success" 
                           StartIcon="@Icons.Material.Filled.Download"
                           OnClick="ExportToExcel">
                    خروجی Excel
                </MudButton>
            </div>

            <MudDataGrid T="UserWeeklyBalanceModel" @ref="_grid"
                         ServerData="@(new Func<GridState<UserWeeklyBalanceModel>, Task<GridData<UserWeeklyBalanceModel>>>(ServerReload))"
                         Filterable="true" 
                         Hover="true">
                <Columns>
                    <PropertyColumn Property="x => x.UserId" Title="شناسه" />
                    <PropertyColumn Property="x => x.UserFullName" Title="نام کاربر" />
                    <PropertyColumn Property="x => x.WeekDisplayName" Title="هفته" />
                    
                    <TemplateColumn Title="چپ (جدید + قبلی = مجموع)">
                        <CellTemplate>
                            <MudStack Row="true" Spacing="1" AlignItems="AlignItems.Center">
                                <MudTooltip Text="اعضای جدید این هفته">
                                    <MudChip T="string" Color="Color.Success" Size="Size.Small">
                                        @context.Item.LeftNewMembers
                                    </MudChip>
                                </MudTooltip>
                                <MudText>+</MudText>
                                <MudTooltip Text="باقیمانده از هفته قبل">
                                    <MudChip T="string" Color="Color.Default" Size="Size.Small">
                                        @context.Item.LeftCarryover
                                    </MudChip>
                                </MudTooltip>
                                <MudText>=</MudText>
                                <MudTooltip Text="مجموع موجودی چپ">
                                    <MudChip T="string" Color="Color.Primary" Size="Size.Small">
                                        <strong>@context.Item.LeftTotal</strong>
                                    </MudChip>
                                </MudTooltip>
                            </MudStack>
                        </CellTemplate>
                    </TemplateColumn>
                    
                    <TemplateColumn Title="راست (جدید + قبلی = مجموع)">
                        <CellTemplate>
                            <MudStack Row="true" Spacing="1" AlignItems="AlignItems.Center">
                                <MudTooltip Text="اعضای جدید این هفته">
                                    <MudChip T="string" Color="Color.Warning" Size="Size.Small">
                                        @context.Item.RightNewMembers
                                    </MudChip>
                                </MudTooltip>
                                <MudText>+</MudText>
                                <MudTooltip Text="باقیمانده از هفته قبل">
                                    <MudChip T="string" Color="Color.Default" Size="Size.Small">
                                        @context.Item.RightCarryover
                                    </MudChip>
                                </MudTooltip>
                                <MudText>=</MudText>
                                <MudTooltip Text="مجموع موجودی راست">
                                    <MudChip T="string" Color="Color.Primary" Size="Size.Small">
                                        <strong>@context.Item.RightTotal</strong>
                                    </MudChip>
                                </MudTooltip>
                            </MudStack>
                        </CellTemplate>
                    </TemplateColumn>
                    
                    <PropertyColumn Property="x => x.MatchedBalance" Title="تعادل">
                        <CellTemplate>
                            <MudChip T="string" Color="Color.Info" Size="Size.Small">
                                <strong>@context.Item.MatchedBalance</strong>
                            </MudChip>
                        </CellTemplate>
                    </PropertyColumn>
                    <PropertyColumn Property="x => x.PoolContribution" Title="سهم از استخر">
                        <CellTemplate>
                            @context.Item.PoolContribution.ToString("N0") تومان
                        </CellTemplate>
                    </PropertyColumn>
                    <PropertyColumn Property="x => x.IsExpired" Title="وضعیت">
                        <CellTemplate>
                            <MudChip T="string" Color="@(context.Item.IsExpired ? Color.Error : Color.Success)" Size="Size.Small">
                                @(context.Item.IsExpired ? "منقضی" : "فعال")
                            </MudChip>
                        </CellTemplate>
                    </PropertyColumn>
                    <TemplateColumn Title="عملیات">
                        <CellTemplate>
                            <MudButton Size="Size.Small" 
                                       Variant="Variant.Text" 
                                       Color="Color.Primary"
                                       StartIcon="@Icons.Material.Filled.Person"
                                       Href="@($"/network/user-info/{context.Item.UserId}")">
                                مشاهده کاربر
                            </MudButton>
                        </CellTemplate>
                    </TemplateColumn>
                </Columns>
            <NoRecordsContent>
                <MudAlert Severity="Severity.Info" Dense="true" Variant="Variant.Text" Class="my-4">موردی یافت نشد.</MudAlert>
            </NoRecordsContent>
                <PagerContent>
                    <MudDataGridPager T="UserWeeklyBalanceModel" 
                                      PageSizeOptions="new int[] { 10, 25, 50, 100 }" />
                </PagerContent>
            </MudDataGrid>
        </MudCardContent>
    </MudCard>

    <MudCard Class="mt-4">
        <MudCardContent>
            <MudGrid>
                <MudItem xs="12" md="4">
                    <MudPaper Elevation="0" Class="pa-4 text-center">
                        <MudText Typo="Typo.h6" Color="Color.Success">مجموع موجودی چپ</MudText>
                        <MudText Typo="Typo.h4">@_totalLeftBalance.ToString("N0")</MudText>
                    </MudPaper>
                </MudItem>
                <MudItem xs="12" md="4">
                    <MudPaper Elevation="0" Class="pa-4 text-center">
                        <MudText Typo="Typo.h6" Color="Color.Warning">مجموع موجودی راست</MudText>
                        <MudText Typo="Typo.h4">@_totalRightBalance.ToString("N0")</MudText>
                    </MudPaper>
                </MudItem>
                <MudItem xs="12" md="4">
                    <MudPaper Elevation="0" Class="pa-4 text-center">
                        <MudText Typo="Typo.h6" Color="Color.Info">مجموع تطبیق‌یافته</MudText>
                        <MudText Typo="Typo.h4">@_totalMatchedBalance.ToString("N0")</MudText>
                    </MudPaper>
                </MudItem>
            </MudGrid>
        </MudCardContent>
    </MudCard>
</div>

@code {
    [Inject] public CommissionContract.CommissionContractClient CommissionClient { get; set; }
private MudDataGrid <UserWeeklyBalanceModel> _grid { get; set; }
    private long? _filterUserId = null;
    private long? _filterWeekDefinitionId = null;
    private int? _minBalance = null;
    private int? _maxBalance = null;
    private bool _onlyActive = false;

    private long _totalLeftBalance = 0;
    private long _totalRightBalance = 0;
    private long _totalMatchedBalance = 0;

    private async Task<GridData<UserWeeklyBalanceModel>> ServerReload(GridState<UserWeeklyBalanceModel> state)
    {
        try
        {
            var request = new GetUserWeeklyBalancesRequest
            {
                OnlyActive = _onlyActive,
                PageIndex = state.Page + 1,
                PageSize = state.PageSize
            };

            if (_filterUserId.HasValue && _filterUserId.Value > 0)
            {
                request.UserId = _filterUserId.Value;
            }

            if (_filterWeekDefinitionId.HasValue && _filterWeekDefinitionId.Value > 0)
            {
                request.WeekDefinitionId = _filterWeekDefinitionId.Value;
            }

            var response = await CommissionClient.GetUserWeeklyBalancesAsync(request);

            var items = response.Models.Select(b => new UserWeeklyBalanceModel
            {
                UserId = b.UserId,
                UserFullName = b.UserFullName,
                WeekDisplayName = b.WeekDisplayName,
                LeftNewMembers = b.LeftLegNewMembers,
                LeftCarryover = b.LeftLegCarryover,
                LeftTotal = b.LeftLegTotal,
                RightNewMembers = b.RightLegNewMembers,
                RightCarryover = b.RightLegCarryover,
                RightTotal = b.RightLegTotal,
                MatchedBalance = b.TotalBalances,
                PoolContribution = b.WeeklyPoolContribution,
                CalculatedAt = b.CalculatedAt?.ToDateTime(),
                IsExpired = b.IsExpired
            }).ToList();

            // Apply balance range filter if specified
            if (_minBalance.HasValue || _maxBalance.HasValue)
            {
                items = items.Where(b => 
                    (!_minBalance.HasValue || b.MatchedBalance >= _minBalance.Value) &&
                    (!_maxBalance.HasValue || b.MatchedBalance <= _maxBalance.Value)
                ).ToList();
            }

            CalculateTotals(items);

            return new GridData<UserWeeklyBalanceModel>
            {
                Items = items,
                TotalItems = (int)(response.MetaData?.TotalCount ?? 0)
            };
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا در بارگذاری داده‌ها: {ex.Message}", Severity.Error);
            return new GridData<UserWeeklyBalanceModel> { Items = new List<UserWeeklyBalanceModel>(), TotalItems = 0 };
        }
    }

    private async Task ApplyFilter()
    {
       await _grid.ReloadServerData();
    }

    private void CalculateTotals(List<UserWeeklyBalanceModel> items)
    {
        _totalLeftBalance = items.Sum(b => (long)b.LeftTotal);
        _totalRightBalance = items.Sum(b => (long)b.RightTotal);
        _totalMatchedBalance = items.Sum(b => (long)b.MatchedBalance);
    }

    private async Task ExportToExcel()
    {
        var confirmed = await DialogService.ShowMessageBox(
            "خروجی Excel",
            "این ویژگی به زودی اضافه خواهد شد.",
            yesText: "باشه");
        
        // Future enhancement: Export to Excel using EPPlus or ClosedXML library
        // Install: dotnet add package EPPlus or ClosedXML
    }

    private class UserWeeklyBalanceModel
    {
        public long UserId { get; set; }
        public string UserFullName { get; set; } = string.Empty;
        public string WeekDisplayName { get; set; }
        
        // چپ
        public int LeftNewMembers { get; set; }
        public int LeftCarryover { get; set; }
        public int LeftTotal { get; set; }
        
        // راست
        public int RightNewMembers { get; set; }
        public int RightCarryover { get; set; }
        public int RightTotal { get; set; }
        
        public int MatchedBalance { get; set; }
        public long PoolContribution { get; set; }
        public DateTime? CalculatedAt { get; set; }
        public bool IsExpired { get; set; }
    }
}
