@page "/commission/reports"

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

<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="4">
                    <WeekNumberPicker Label="از هفته"
                                      @bind-SelectedWeekDefinitionId="_filterFromWeekId"
                                      PastWeeksCount="24" />
                </MudItem>
                <MudItem xs="12" md="4">
                    <WeekNumberPicker Label="تا هفته"
                                      @bind-SelectedWeekDefinitionId="_filterToWeekId"
                                      PastWeeksCount="24" />
                </MudItem>
                <MudItem xs="12" md="4" Class="d-flex align-center">
                    <MudStack Row="true" Spacing="2" Style="width:100%">
                        <MudButton Variant="Variant.Filled" 
                                   Color="Color.Primary" 
                                   OnClick="ApplyFilter"
                                   StartIcon="@Icons.Material.Filled.Search"
                                   FullWidth="true">
                            جستجو
                        </MudButton>
                        <MudButton Variant="Variant.Outlined" 
                                   Color="Color.Info" 
                                   OnClick="ExportToExcel"
                                   StartIcon="@Icons.Material.Filled.FileDownload"
                                   FullWidth="true">
                            خروجی Excel
                        </MudButton>
                    </MudStack>
                </MudItem>
            </MudGrid>
        </MudCardContent>
    </MudCard>

    <MudCard>
        <MudCardContent>
            @if (_loading)
            {
                <MudProgressCircular Color="Color.Primary" Indeterminate="true" />
            }
            else if (_reports == null || !_reports.Any())
            {
                <MudAlert Severity="Severity.Info">هیچ گزارشی یافت نشد</MudAlert>
            }
            else
            {
                <MudDataGrid T="WeeklyPoolReportModel" 
                             Items="@_reports" 
                             Hover="true" 
                             Filterable="true"
                             SortMode="SortMode.Multiple">
                    <Columns>
                        <PropertyColumn Property="x => x.WeekDisplayName" Title="هفته" />
                        <PropertyColumn Property="x => x.TotalPoolAmount" Title="مبلغ کل استخر" Format="N0">
                            <CellTemplate>
                                <MudText>@context.Item.TotalPoolAmount.ToString("N0") تومان</MudText>
                            </CellTemplate>
                        </PropertyColumn>
                        <PropertyColumn Property="x => x.TotalBalances" Title="مجموع موجودی‌ها" />
                        <PropertyColumn Property="x => x.ValuePerBalance" Title="ارزش هر موجودی" Format="N0">
                            <CellTemplate>
                                <MudText>@context.Item.ValuePerBalance.ToString("N0") تومان</MudText>
                            </CellTemplate>
                        </PropertyColumn>
                        <PropertyColumn Property="x => x.IsCalculated" Title="وضعیت">
                            <CellTemplate>
                                <MudChip T="string" 
                                         Color="@(context.Item.IsCalculated ? Color.Success : Color.Warning)" 
                                         Size="Size.Small">
                                    @(context.Item.IsCalculated ? "محاسبه شده" : "در انتظار")
                                </MudChip>
                            </CellTemplate>
                        </PropertyColumn>
                        <PropertyColumn Property="x => x.CalculatedAt" Title="تاریخ محاسبه">
                            <CellTemplate>
                                @if (context.Item.CalculatedAt != null)
                                {
                                    <MudText>@context.Item.CalculatedAt.ToDateTime().MiladiToJalaliWithTime()</MudText>
                                }
                                else
                                {
                                    <MudText Color="Color.Secondary">-</MudText>
                                }
                            </CellTemplate>
                        </PropertyColumn>
                        <TemplateColumn Title="عملیات">
                            <CellTemplate>
                                <MudButton Size="Size.Small" 
                                           Variant="Variant.Text" 
                                           Color="Color.Primary"
                                           StartIcon="@Icons.Material.Filled.Visibility"
                                           OnClick="@(() => ViewDetails(context.Item))">
                                    جزئیات
                                </MudButton>
                                <MudButton Size="Size.Small" 
                                           Variant="Variant.Text" 
                                           Color="Color.Info"
                                           StartIcon="@Icons.Material.Filled.People"
                                           Href="@($"/commission/payouts?weekDefinitionId={context.Item.WeekDefinitionId}")">
                                    پرداخت‌ها
                                </MudButton>
                            </CellTemplate>
                        </TemplateColumn>
                    </Columns>
                </MudDataGrid>
            }
        </MudCardContent>
    </MudCard>

    <MudCard Class="mt-4">
        <MudCardContent>
            <MudGrid>
                <MudItem xs="12" md="3">
                    <MudPaper Elevation="0" Class="pa-4 text-center">
                        <MudText Typo="Typo.h6" Color="Color.Primary">مجموع استخرها</MudText>
                        <MudText Typo="Typo.h4">@_totalPoolSum.ToString("N0")</MudText>
                        <MudText Typo="Typo.caption" Color="Color.Secondary">تومان</MudText>
                    </MudPaper>
                </MudItem>
                <MudItem xs="12" md="3">
                    <MudPaper Elevation="0" Class="pa-4 text-center">
                        <MudText Typo="Typo.h6" Color="Color.Success">محاسبه شده</MudText>
                        <MudText Typo="Typo.h4">@_calculatedCount</MudText>
                        <MudText Typo="Typo.caption" Color="Color.Secondary">هفته</MudText>
                    </MudPaper>
                </MudItem>
                <MudItem xs="12" md="3">
                    <MudPaper Elevation="0" Class="pa-4 text-center">
                        <MudText Typo="Typo.h6" Color="Color.Warning">در انتظار</MudText>
                        <MudText Typo="Typo.h4">@_pendingCount</MudText>
                        <MudText Typo="Typo.caption" Color="Color.Secondary">هفته</MudText>
                    </MudPaper>
                </MudItem>
                <MudItem xs="12" md="3">
                    <MudPaper Elevation="0" Class="pa-4 text-center">
                        <MudText Typo="Typo.h6" Color="Color.Info">میانگین ارزش</MudText>
                        <MudText Typo="Typo.h4">@_averageValue.ToString("N0")</MudText>
                        <MudText Typo="Typo.caption" Color="Color.Secondary">تومان</MudText>
                    </MudPaper>
                </MudItem>
            </MudGrid>
        </MudCardContent>
    </MudCard>
</div>

@code {
    [Inject] public CommissionContract.CommissionContractClient CommissionClient { get; set; }

    private List<WeeklyPoolReportModel> _reports = new();
    private bool _loading = false;
    private long? _filterFromWeekId;
    private long? _filterToWeekId;

    // Statistics
    private long _totalPoolSum = 0;
    private int _calculatedCount = 0;
    private int _pendingCount = 0;
    private long _averageValue = 0;

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

    private async Task LoadData()
    {
        _loading = true;
        try
        {
            var request = new GetAllWeeklyPoolsRequest
            {
                PageIndex = 1,
                PageSize = 100
            };

            if (_filterFromWeekId.HasValue && _filterFromWeekId.Value > 0)
            {
                request.FromWeekDefinitionId = _filterFromWeekId.Value;
            }

            if (_filterToWeekId.HasValue && _filterToWeekId.Value > 0)
            {
                request.ToWeekDefinitionId = _filterToWeekId.Value;
            }

            var response = await CommissionClient.GetAllWeeklyPoolsAsync(request);

            _reports = response.Models.Select(x => new WeeklyPoolReportModel
            {
                WeekDefinitionId = x.WeekDefinitionId,
                WeekDisplayName = x.WeekDisplayName,
                TotalPoolAmount = x.TotalPoolAmount,
                TotalBalances = x.TotalBalances,
                ValuePerBalance = x.ValuePerBalance,
                IsCalculated = x.IsCalculated,
                CalculatedAt = x.CalculatedAt
            }).ToList();

            CalculateStatistics();
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا در بارگذاری داده‌ها: {ex.Message}", Severity.Error);
        }
        finally
        {
            _loading = false;
        }
    }

    private async Task ApplyFilter()
    {
        await LoadData();
    }

    private void ViewDetails(WeeklyPoolReportModel report)
    {
        Navigation.NavigateTo($"/commission/dashboard?weekId={report.WeekDefinitionId}");
    }

    private void CalculateStatistics()
    {
        if (_reports == null || !_reports.Any()) return;

        _totalPoolSum = _reports.Sum(r => r.TotalPoolAmount);
        _calculatedCount = _reports.Count(r => r.IsCalculated);
        _pendingCount = _reports.Count(r => !r.IsCalculated);
        _averageValue = _reports.Any() ? (long)_reports.Average(r => r.ValuePerBalance) : 0;
    }



    // Model for weekly pool reports
    private class WeeklyPoolReportModel
    {
        public long WeekDefinitionId { get; set; }
        public string WeekDisplayName { get; set; } = "";
        public long TotalPoolAmount { get; set; }
        public int TotalBalances { get; set; }
        public long ValuePerBalance { get; set; }
        public bool IsCalculated { get; set; }
        public Timestamp CalculatedAt { get; set; }
    }
}
