@using BackOffice.Services.DiscountOrder

@inject IDiscountOrderService DiscountOrderService

<MudCard Class="mb-4">
    <MudCardHeader>
        <CardHeaderContent>
            <MudText Typo="Typo.h6">
                <MudIcon Icon="@Icons.Material.Filled.Discount" Class="mr-2" />
                آمار فروشگاه تخفیفی (۷ روز اخیر)
            </MudText>
        </CardHeaderContent>
    </MudCardHeader>
    <MudCardContent>
        @if (_loading)
        {
            <MudProgressCircular Color="Color.Primary" Indeterminate="true" />
        }
        else
        {
            <MudGrid>
                <MudItem xs="12" md="4">
                    <MudStack Spacing="1">
                        <MudText Typo="Typo.body2" Color="Color.Secondary">تعداد سفارش‌ها (۷ روز)</MudText>
                        <MudText Typo="Typo.h5">@_stats.TotalOrdersLast7Days.ToString("N0")</MudText>
                        <MudText Typo="Typo.caption" Color="Color.Secondary">
                            امروز: @_stats.TodayOrders.ToString("N0")
                        </MudText>
                    </MudStack>
                </MudItem>
                <MudItem xs="12" md="4">
                    <MudStack Spacing="1">
                        <MudText Typo="Typo.body2" Color="Color.Secondary">مجموع فروش (۷ روز)</MudText>
                        <MudText Typo="Typo.h5" Color="Color.Primary">
                            @_stats.TotalSalesLast7Days.ToString("N0") تومان
                        </MudText>
                        <MudText Typo="Typo.caption" Color="Color.Secondary">
                            امروز: @_stats.TodaySales.ToString("N0") تومان
                        </MudText>
                    </MudStack>
                </MudItem>
                <MudItem xs="12" md="4">
                    <MudStack Spacing="1">
                        <MudText Typo="Typo.body2" Color="Color.Secondary">میانگین مبلغ هر سفارش</MudText>
                        <MudText Typo="Typo.h5">
                            @_stats.AverageOrderAmount.ToString("N0") تومان
                        </MudText>
                    </MudStack>
                </MudItem>
            </MudGrid>

            <MudDivider Class="my-2" />

            <MudText Typo="Typo.subtitle2" Class="mb-2">روند فروش روزانه (۷ روز اخیر)</MudText>
            @if (_dailyLabels.Length == 0)
            {
                <MudText Typo="Typo.caption" Color="Color.Secondary">
                    برای این بازه زمانی سفارشی ثبت نشده است.
                </MudText>
            }
            else
            {
                <MudChart ChartType="ChartType.Line"
                          ChartSeries="@_dailySeries"
                          XAxisLabels="@_dailyLabels"
                          Height="200px" />
            }
        }
    </MudCardContent>
</MudCard>

@code {
    private bool _loading;
    private DiscountShopStats _stats = new();
    private string[] _dailyLabels = Array.Empty<string>();
    private List<ChartSeries> _dailySeries = new();

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

    private async Task LoadStatsAsync()
    {
        _loading = true;
        try
        {
            var today = DateTime.Today;
            var fromDate = today.AddDays(-6);

            var filter = new OrderFilterDto
            {
                PageNumber = 1,
                PageSize = 1000 // Get all for stats
            };

            var result = await DiscountOrderService.GetOrdersAsync(filter);
            var orders = result.Orders.Where(o => o.Created >= fromDate && o.Created <= today.AddDays(1).AddSeconds(-1)).ToList();

            _stats = new DiscountShopStats();

            if (orders.Count > 0)
            {
                _stats.TotalOrdersLast7Days = orders.Count;
                _stats.TotalSalesLast7Days = orders.Sum(o => o.TotalPrice);

                _stats.TodayOrders = orders.Count(o => o.Created?.Date == today);
                _stats.TodaySales = orders.Where(o => o.Created?.Date == today)
                    .Sum(o => o.TotalPrice);

                _stats.AverageOrderAmount = _stats.TotalOrdersLast7Days > 0
                    ? _stats.TotalSalesLast7Days / _stats.TotalOrdersLast7Days
                    : 0;

                var groups = orders
                    .Where(o => o.Created.HasValue)
                    .GroupBy(o => o.Created!.Value.Date)
                    .OrderBy(g => g.Key)
                    .ToList();

                _dailyLabels = groups.Select(g => { var j = g.Key.MiladiToJalali(); return j.Length >= 7 ? j.Substring(5) : j; }).ToArray();

                _dailySeries = new List<ChartSeries>
                {
                    new()
                    {
                        Name = "مبلغ فروش",
                        Data = groups.Select(g => (double)g.Sum(o => o.TotalPrice)).ToArray()
                    }
                };
            }
            else
            {
                _dailyLabels = Array.Empty<string>();
                _dailySeries = new List<ChartSeries>();
            }
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا در بارگذاری آمار فروشگاه تخفیفی: {ex.Message}", Severity.Warning);
            _stats = new DiscountShopStats();
            _dailyLabels = Array.Empty<string>();
            _dailySeries = new List<ChartSeries>();
        }
        finally
        {
            _loading = false;
        }
    }

    private class DiscountShopStats
    {
        public int TotalOrdersLast7Days { get; set; }
        public long TotalSalesLast7Days { get; set; }
        public int TodayOrders { get; set; }
        public long TodaySales { get; set; }
        public long AverageOrderAmount { get; set; }
    }
}

