@attribute [Route(RouteConstance.HomePage)]
@attribute [Route("/dashboard/overview")]

@using CMSMicroservice.Protobuf.Protos.User
@using CMSMicroservice.Protobuf.Protos.UserOrder
@using CMSMicroservice.Protobuf.Protos
@using CMSMicroservice.Protobuf.Protos.Products
@using CMSMicroservice.Protobuf.Protos.Package
@using CMSMicroservice.Protobuf.Protos.Category
@using CMSMicroservice.Protobuf.Protos.Commission
@using CMSMicroservice.Protobuf.Protos.ClubMembership
@inject UserContract.UserContractClient UserContract
@inject UserOrderContract.UserOrderContractClient UserOrderContract
@inject ProductsContract.ProductsContractClient ProductsContract
@inject PackageContract.PackageContractClient PackageContract
@inject CategoryContract.CategoryContractClient CategoryContract
@inject CommissionContract.CommissionContractClient CommissionClient
@inject ClubMembershipContract.ClubMembershipContractClient ClubClient

<MudStack Spacing="3">

    @* ── عنوان و وضعیت بارگذاری ── *@
    <MudStack Row="true" AlignItems="AlignItems.Center" Justify="Justify.SpaceBetween">
        <MudText Typo="Typo.h5">داشبورد مدیریت</MudText>
        @if (_loading)
        {
            <MudProgressCircular Color="Color.Primary" Size="Size.Small" Indeterminate="true" />
        }
    </MudStack>

    @* ── آمار کلی فروشگاه ── *@
    <MudGrid Spacing="2">
        <MudItem xs="6" sm="4" md="2">
            <MudPaper Class="pa-3 rounded-lg" Elevation="0" Outlined="true">
                <MudStack Spacing="1" AlignItems="AlignItems.Start">
                    <MudIcon Icon="@Icons.Material.Filled.People" Color="Color.Primary" Size="Size.Small" />
                    <MudText Typo="Typo.caption" Color="Color.Secondary">کاربران</MudText>
                    <MudText Typo="Typo.h6">@_totalUsers.ToString("N0")</MudText>
                </MudStack>
            </MudPaper>
        </MudItem>
        <MudItem xs="6" sm="4" md="2">
            <MudPaper Class="pa-3 rounded-lg" Elevation="0" Outlined="true">
                <MudStack Spacing="1" AlignItems="AlignItems.Start">
                    <MudIcon Icon="@Icons.Material.Filled.ShoppingBag" Color="Color.Info" Size="Size.Small" />
                    <MudText Typo="Typo.caption" Color="Color.Secondary">محصولات</MudText>
                    <MudText Typo="Typo.h6">@_totalProducts.ToString("N0")</MudText>
                </MudStack>
            </MudPaper>
        </MudItem>
        <MudItem xs="6" sm="4" md="2">
            <MudPaper Class="pa-3 rounded-lg" Elevation="0" Outlined="true">
                <MudStack Spacing="1" AlignItems="AlignItems.Start">
                    <MudIcon Icon="@Icons.Material.Filled.Inventory2" Color="Color.Secondary" Size="Size.Small" />
                    <MudText Typo="Typo.caption" Color="Color.Secondary">پکیج‌ها</MudText>
                    <MudText Typo="Typo.h6">@_totalPackages.ToString("N0")</MudText>
                </MudStack>
            </MudPaper>
        </MudItem>
        <MudItem xs="6" sm="4" md="2">
            <MudPaper Class="pa-3 rounded-lg" Elevation="0" Outlined="true">
                <MudStack Spacing="1" AlignItems="AlignItems.Start">
                    <MudIcon Icon="@Icons.Material.Filled.Category" Color="Color.Tertiary" Size="Size.Small" />
                    <MudText Typo="Typo.caption" Color="Color.Secondary">دسته‌بندی‌ها</MudText>
                    <MudText Typo="Typo.h6">@_totalCategories.ToString("N0")</MudText>
                </MudStack>
            </MudPaper>
        </MudItem>
        <MudItem xs="6" sm="4" md="2">
            <MudPaper Class="pa-3 rounded-lg" Elevation="0" Outlined="true">
                <MudStack Spacing="1" AlignItems="AlignItems.Start">
                    <MudIcon Icon="@Icons.Material.Filled.Receipt" Color="Color.Success" Size="Size.Small" />
                    <MudText Typo="Typo.caption" Color="Color.Secondary">سفارش‌ها</MudText>
                    <MudText Typo="Typo.h6">@_totalOrders.ToString("N0")</MudText>
                </MudStack>
            </MudPaper>
        </MudItem>
        <MudItem xs="6" sm="4" md="2">
            <MudPaper Class="pa-3 rounded-lg" Elevation="0" Outlined="true">
                <MudStack Spacing="1" AlignItems="AlignItems.Start">
                    <MudIcon Icon="@Icons.Material.Filled.Paid" Color="Color.Warning" Size="Size.Small" />
                    <MudText Typo="Typo.caption" Color="Color.Secondary">مبلغ پرداخت‌شده</MudText>
                    <MudText Typo="Typo.h6">@_totalPaidAmount.ToString("N0")</MudText>
                </MudStack>
            </MudPaper>
        </MudItem>
    </MudGrid>

    @* ── کمیسیون هفته جاری ── *@
    <MudPaper Class="pa-4 rounded-lg" Outlined="true">
        <MudStack Row="true" AlignItems="AlignItems.Center" Justify="Justify.SpaceBetween" Class="mb-3">
            <MudStack Row="true" AlignItems="AlignItems.Center" Spacing="2">
                <MudIcon Icon="@Icons.Material.Filled.AccountBalanceWallet" Color="Color.Primary" />
                <MudText Typo="Typo.subtitle1">کمیسیون هفته جاری</MudText>
            </MudStack>
            <MudButton Variant="Variant.Text" Color="Color.Primary" Href="/commission/dashboard" Size="Size.Small">
                جزئیات بیشتر
            </MudButton>
        </MudStack>
        <MudGrid Spacing="2">
            <MudItem xs="12" sm="6" md="3">
                <MudStack Spacing="0">
                    <MudText Typo="Typo.caption" Color="Color.Secondary">هفته جاری</MudText>
                    <MudText Typo="Typo.h6">@(_currentWeekDisplayName ?? "—")</MudText>
                </MudStack>
            </MudItem>
            <MudItem xs="12" sm="6" md="3">
                <MudStack Spacing="0">
                    <MudText Typo="Typo.caption" Color="Color.Secondary">مبلغ کل استخر</MudText>
                    <MudText Typo="Typo.h6" Color="Color.Primary">
                        @(_currentPool?.TotalPoolAmount.ToString("N0") ?? "0") تومان
                    </MudText>
                </MudStack>
            </MudItem>
            <MudItem xs="12" sm="6" md="3">
                <MudStack Spacing="0">
                    <MudText Typo="Typo.caption" Color="Color.Secondary">مجموع موجودی‌ها</MudText>
                    <MudText Typo="Typo.h6">@(_currentPool?.TotalBalances.ToString("N0") ?? "0")</MudText>
                </MudStack>
            </MudItem>
            <MudItem xs="12" sm="6" md="3">
                <MudStack Spacing="0">
                    <MudText Typo="Typo.caption" Color="Color.Secondary">وضعیت</MudText>
                    <MudChip T="string" Color="@(_currentPool?.IsCalculated == true ? Color.Success : Color.Warning)"
                             Size="Size.Small">
                        @(_currentPool?.IsCalculated == true ? "محاسبه شده" : "در انتظار")
                    </MudChip>
                </MudStack>
            </MudItem>
        </MudGrid>
    </MudPaper>

    @* ── آمار باشگاه ── *@
    <MudPaper Class="pa-4 rounded-lg" Outlined="true">
        <MudStack Row="true" AlignItems="AlignItems.Center" Justify="Justify.SpaceBetween" Class="mb-3">
            <MudStack Row="true" AlignItems="AlignItems.Center" Spacing="2">
                <MudIcon Icon="@Icons.Material.Filled.CardMembership" Color="Color.Secondary" />
                <MudText Typo="Typo.subtitle1">عضویت باشگاه</MudText>
            </MudStack>
            <MudButton Variant="Variant.Text" Color="Color.Primary" Href="/club/members" Size="Size.Small">
                مشاهده اعضا
            </MudButton>
        </MudStack>
        <MudGrid Spacing="2">
            <MudItem xs="12" sm="4">
                <MudStack Spacing="0">
                    <MudText Typo="Typo.caption" Color="Color.Secondary">کل اعضا</MudText>
                    <MudText Typo="Typo.h6" Color="Color.Primary">@_totalClubMembers.ToString("N0")</MudText>
                </MudStack>
            </MudItem>
            <MudItem xs="12" sm="4">
                <MudStack Spacing="0">
                    <MudText Typo="Typo.caption" Color="Color.Secondary">فعال</MudText>
                    <MudText Typo="Typo.h6" Color="Color.Success">@_activeClubMembers.ToString("N0")</MudText>
                </MudStack>
            </MudItem>
            <MudItem xs="12" sm="4">
                <MudStack Spacing="0">
                    <MudText Typo="Typo.caption" Color="Color.Secondary">غیرفعال</MudText>
                    <MudText Typo="Typo.h6" Color="Color.Warning">@_inactiveClubMembers.ToString("N0")</MudText>
                </MudStack>
            </MudItem>
        </MudGrid>
    </MudPaper>

    @* ── آخرین سفارش‌ها ── *@
    <MudPaper Class="pa-4 rounded-lg" Outlined="true">
        <MudText Typo="Typo.subtitle1" Class="mb-2">آخرین سفارش‌های پرداخت‌شده</MudText>
        @if (_lastOrders.Count == 0)
        {
            <MudAlert Severity="Severity.Info" Dense="true" Variant="Variant.Text">سفارشی ثبت نشده است.</MudAlert>
        }
        else
        {
            <MudTable Items="_lastOrders" Dense="true" Hover="true" Elevation="0">
                <HeaderContent>
                    <MudTh>شناسه</MudTh>
                    <MudTh>کاربر</MudTh>
                    <MudTh>مبلغ</MudTh>
                    <MudTh>تاریخ پرداخت</MudTh>
                </HeaderContent>
                <RowTemplate>
                    <MudTd>@context.Id</MudTd>
                    <MudTd>@context.UserFullName</MudTd>
                    <MudTd>@context.Amount.ToString("N0")</MudTd>
                    <MudTd>@(context.PaymentDate != null ? context.PaymentDate.ToDateTime().MiladiToJalali() : "—")</MudTd>
                </RowTemplate>
            </MudTable>
        }
    </MudPaper>

    @* ── دسترسی سریع ── *@
    <MudPaper Class="pa-4 rounded-lg" Outlined="true">
        <MudStack Row="true" AlignItems="AlignItems.Center" Spacing="2" Class="mb-3">
            <MudIcon Icon="@Icons.Material.Filled.Speed" Color="Color.Info" />
            <MudText Typo="Typo.subtitle1">دسترسی سریع</MudText>
        </MudStack>
        <MudGrid Spacing="2">
            <MudItem xs="6" md="4">
                <MudButton Variant="Variant.Outlined" Color="Color.Primary" FullWidth="true"
                           Href="/commission/dashboard" StartIcon="@Icons.Material.Filled.AccountBalanceWallet">
                    داشبورد کمیسیون
                </MudButton>
            </MudItem>
            <MudItem xs="6" md="4">
                <MudButton Variant="Variant.Outlined" Color="Color.Secondary" FullWidth="true"
                           Href="/commission/payouts" StartIcon="@Icons.Material.Filled.Payments">
                    واریزی‌ها
                </MudButton>
            </MudItem>
            <MudItem xs="6" md="4">
                <MudButton Variant="Variant.Outlined" Color="Color.Warning" FullWidth="true"
                           Href="/commission/withdrawals" StartIcon="@Icons.Material.Filled.RequestQuote">
                    درخواست‌های برداشت
                </MudButton>
            </MudItem>
            <MudItem xs="6" md="4">
                <MudButton Variant="Variant.Outlined" Color="Color.Info" FullWidth="true"
                           Href="/network/tree" StartIcon="@Icons.Material.Filled.AccountTree">
                    درخت شبکه
                </MudButton>
            </MudItem>
            <MudItem xs="6" md="4">
                <MudButton Variant="Variant.Outlined" Color="Color.Success" FullWidth="true"
                           Href="/network/balances" StartIcon="@Icons.Material.Filled.AccountBalance">
                    گزارش موجودی‌ها
                </MudButton>
            </MudItem>
            <MudItem xs="6" md="4">
                <MudButton Variant="Variant.Outlined" Color="Color.Tertiary" FullWidth="true"
                           Href="/club/members" StartIcon="@Icons.Material.Filled.Groups">
                    مدیریت باشگاه
                </MudButton>
            </MudItem>
        </MudGrid>
    </MudPaper>
</MudStack>

@code {
    private bool _loading = true;
    private long _totalUsers;
    private long _totalOrders;
    private long _paidOrders;
    private long _totalPaidAmount;
    private long _totalProducts;
    private long _totalPackages;
    private long _totalCategories;
    private readonly List<GetUserOrderResponse> _lastOrders = new();

    // Commission
    private string? _currentWeekDisplayName;
    private long _currentWeekDefinitionId;
    private GetWeeklyCommissionPoolResponse? _currentPool;

    // Club
    private long _totalClubMembers;
    private long _activeClubMembers;
    private long _inactiveClubMembers;

    protected override async Task OnInitializedAsync()
    {
        _loading = true;
        try
        {
            // Load all data in parallel for speed
            var tasks = new List<Task>
            {
                LoadCmsStats(),
                LoadCommissionStats(),
                LoadClubStats(),
                LoadRecentOrders()
            };
            await Task.WhenAll(tasks);
        }
        catch { /* Individual loaders handle their own errors */ }
        finally
        {
            _loading = false;
        }
    }

    private async Task LoadCmsStats()
    {
        try
        {
            var userCall = UserContract.GetAllUserByFilterAsync(new GetAllUserByFilterRequest
            {
                PaginationState = new() { PageNumber = 1, PageSize = 1 },
                Filter = new()
            });
            var productCall = ProductsContract.GetAllProductsByFilterAsync(new GetAllProductsByFilterRequest
            {
                PaginationState = new() { PageNumber = 1, PageSize = 1 },
                Filter = new()
            });
            var packageCall = PackageContract.GetAllPackageByFilterAsync(new GetAllPackageByFilterRequest
            {
                PaginationState = new() { PageNumber = 1, PageSize = 1 },
                Filter = new()
            });
            var categoryCall = CategoryContract.GetAllCategoryByFilterAsync(new GetAllCategoryByFilterRequest
            {
                PaginationState = new() { PageNumber = 1, PageSize = 1 },
                Filter = new()
            });

            await Task.WhenAll(userCall.ResponseAsync, productCall.ResponseAsync, packageCall.ResponseAsync, categoryCall.ResponseAsync);

            _totalUsers = (await userCall)?.MetaData?.TotalCount ?? 0;
            _totalProducts = (await productCall)?.MetaData?.TotalCount ?? 0;
            _totalPackages = (await packageCall)?.MetaData?.TotalCount ?? 0;
            _totalCategories = (await categoryCall)?.MetaData?.TotalCount ?? 0;
        }
        catch { }
    }

    private async Task LoadCommissionStats()
    {
        try
        {
            var availableWeeks = await CommissionClient.GetAvailableWeeksAsync(new GetAvailableWeeksRequest
            {
                FutureWeeksCount = 0,
                PastWeeksCount = 0
            });
            if (availableWeeks?.CurrentWeek != null)
            {
                _currentWeekDefinitionId = availableWeeks.CurrentWeek.WeekDefinitionId;
                _currentWeekDisplayName = availableWeeks.CurrentWeek.DisplayName;

                _currentPool = await CommissionClient.GetWeeklyCommissionPoolAsync(new GetWeeklyCommissionPoolRequest
                {
                    WeekDefinitionId = _currentWeekDefinitionId
                });
            }
        }
        catch { }
    }

    private async Task LoadClubStats()
    {
        try
        {
            var allReq = ClubClient.GetAllClubMembershipsAsync(new GetAllClubMembershipsRequest { PageIndex = 1, PageSize = 1 });
            var activeReq = ClubClient.GetAllClubMembershipsAsync(new GetAllClubMembershipsRequest { PageIndex = 1, PageSize = 1, IsActive = true });

            await Task.WhenAll(allReq.ResponseAsync, activeReq.ResponseAsync);

            _totalClubMembers = (await allReq).MetaData?.TotalCount ?? 0;
            _activeClubMembers = (await activeReq).MetaData?.TotalCount ?? 0;
            _inactiveClubMembers = _totalClubMembers - _activeClubMembers;
        }
        catch { }
    }

    private async Task LoadRecentOrders()
    {
        try
        {
            var orderResult = await UserOrderContract.GetAllUserOrderByFilterAsync(new GetAllUserOrderByFilterRequest
            {
                PaginationState = new() { PageNumber = 1, PageSize = 5 },
            });
            if (orderResult?.Models != null)
            {
                _totalOrders = orderResult.MetaData?.TotalCount ?? 0;
                _paidOrders = orderResult.Models.Count(m => m.PaymentStatus == PaymentStatus.Success);
                _totalPaidAmount = orderResult.Models
                    .Where(m => m.PaymentStatus == PaymentStatus.Success)
                    .Sum(m => m.Amount);

                foreach (var item in orderResult.Models.OrderByDescending(m => m.PaymentDate).Take(5))
                {
                    try
                    {
                        var full = await UserOrderContract.GetUserOrderAsync(new GetUserOrderRequest { Id = item.Id });
                        _lastOrders.Add(full);
                    }
                    catch { }
                }
            }
        }
        catch { }
    }
}
