@using Microsoft.AspNetCore.Components.Authorization
@using CMSMicroservice.Protobuf.Protos.Commission
@inject BackOffice.Services.Authorization.IAuthorizationService AuthorizationService
@inject CommissionContract.CommissionContractClient CommissionClient

<MudNavMenu Bordered="false" Class="nav-menu">
    <MudText Class="nav-menu__title" Typo="Typo.subtitle2">داشبورد</MudText>
    <MudDivider Class="mb-2" />

    @if (CanViewDashboard)
    {
        <MudNavLink Match="NavLinkMatch.Prefix"
                    Href="/"
                    Icon="@Icons.Material.Filled.Dashboard">
            داشبورد
        </MudNavLink>
    }

    <MudDivider Class="my-2" />
    <MudText Class="nav-menu__title" Typo="Typo.subtitle2">کمیسیون و شبکه</MudText>

    <MudNavGroup Title="کمیسیون" Icon="@Icons.Material.Filled.AccountBalanceWallet" Expanded="false">
        <MudNavLink Match="NavLinkMatch.Prefix"
                    Href="/commission/dashboard"
                    Icon="@Icons.Material.Filled.Dashboard">
            داشبورد کمیسیون
        </MudNavLink>
        <MudNavLink Match="NavLinkMatch.Prefix"
                    Href="/commission/reports"
                    Icon="@Icons.Material.Filled.Assessment">
            گزارش‌های هفتگی
        </MudNavLink>
        <MudNavLink Match="NavLinkMatch.Prefix"
                    Href="/commission/payouts"
                    Icon="@Icons.Material.Filled.Payments">
            پرداخت کاربران
        </MudNavLink>
        <MudNavLink Match="NavLinkMatch.Prefix"
                    Href="/commission/withdrawals"
                    Icon="@Icons.Material.Filled.RequestQuote">
            <MudBadge Content="@_pendingWithdrawalsCount" 
                      Color="Color.Error" 
                      Overlap="false" 
                      Visible="@(_pendingWithdrawalsCount > 0)"
                      Class="mx-1">
                درخواست‌های برداشت
            </MudBadge>
        </MudNavLink>
        <MudNavLink Match="NavLinkMatch.Prefix"
                    Href="/commission/withdrawal-reports"
                    Icon="@Icons.Material.Filled.BarChart">
            گزارش برداشت‌ها
        </MudNavLink>
    </MudNavGroup>

    <MudNavGroup Title="شبکه" Icon="@Icons.Material.Filled.AccountTree" Expanded="false">
        <MudNavLink Match="NavLinkMatch.Prefix"
                    Href="/network/tree"
                    Icon="@Icons.Material.Filled.AccountTree">
            درخت شبکه
        </MudNavLink>
        <MudNavLink Match="NavLinkMatch.Prefix"
                    Href="/network/balances"
                    Icon="@Icons.Material.Filled.Balance">
            گزارش موجودی‌ها
        </MudNavLink>
        <MudNavLink Match="NavLinkMatch.Prefix"
                    Href="/network/statistics"
                    Icon="@Icons.Material.Filled.BarChart">
            آمار شبکه
        </MudNavLink>
    </MudNavGroup>

    <MudNavGroup Title="باشگاه مشتریان" Icon="@Icons.Material.Filled.CardMembership" Expanded="false">
        <MudNavLink Match="NavLinkMatch.Prefix"
                    Href="/club/members"
                    Icon="@Icons.Material.Filled.Groups">
            اعضا و آمار
        </MudNavLink>
        <MudNavLink Match="NavLinkMatch.Prefix"
                    Href="/club/features"
                    Icon="@Icons.Material.Filled.Star">
            فیچرهای باشگاه
        </MudNavLink>
    </MudNavGroup>

    <MudDivider Class="my-2" />
    <MudText Class="nav-menu__title" Typo="Typo.subtitle2">فروشگاه</MudText>

    <AuthorizeView Roles="Administrator">
        <Authorized>
            @if (CanManagePackages)
            {
                <MudNavLink Match="NavLinkMatch.Prefix"
                            Href="@(RouteConstance.Package)"
                            Icon="@Icons.Material.Filled.Inventory2">
                    پکیج‌ها
                </MudNavLink>
            }

            @if (CanManageProducts)
            {
                <MudNavGroup Title="فروشگاه عادی" Icon="@Icons.Material.Filled.Store" Expanded="false">
                    <MudNavLink Match="NavLinkMatch.Prefix"
                                Href="@(RouteConstance.Products)"
                                Icon="@Icons.Material.Filled.Inventory">
                        محصولات
                    </MudNavLink>
                    <MudNavLink Match="NavLinkMatch.Prefix"
                                Href="@(RouteConstance.Category)"
                                Icon="@Icons.Material.Filled.Category">
                        دسته‌بندی‌ها
                    </MudNavLink>
                    @if (CanViewOrders)
                    {
                        <MudNavLink Match="NavLinkMatch.Prefix"
                                    Href="@(RouteConstance.Orders)"
                                    Icon="@Icons.Material.Filled.ShoppingCart">
                            سفارشات و گزارش
                        </MudNavLink>
                    }
                </MudNavGroup>

                <MudNavGroup Title="انبارداری" Icon="@Icons.Material.Filled.Warehouse" Expanded="false">
                    <MudNavLink Match="NavLinkMatch.Prefix"
                                Href="@(RouteConstance.Inventory)"
                                Icon="@Icons.Material.Filled.Inventory">
                        موجودی انبار
                    </MudNavLink>
                    <MudNavLink Match="NavLinkMatch.Prefix"
                                Href="@(RouteConstance.InventoryLowStock)"
                                Icon="@Icons.Material.Filled.Warning">
                        محصولات کم‌موجود
                    </MudNavLink>
                    <MudNavLink Match="NavLinkMatch.Prefix"
                                Href="@(RouteConstance.InventoryWarehouses)"
                                Icon="@Icons.Material.Filled.Store">
                        مدیریت انبارها
                    </MudNavLink>
                    <MudNavLink Match="NavLinkMatch.Prefix"
                                Href="@(RouteConstance.InventoryMovements)"
                                Icon="@Icons.Material.Filled.History">
                        تاریخچه تغییرات
                    </MudNavLink>
                </MudNavGroup>
            }

            @if (CanManageDiscountShop)
            {
                <MudNavGroup Title="فروشگاه تخفیفی" Icon="@Icons.Material.Filled.Discount" Expanded="false">
                    <MudNavLink Match="NavLinkMatch.Prefix"
                                Href="/discount-products"
                                Icon="@Icons.Material.Filled.Inventory">
                        محصولات
                    </MudNavLink>
                    <MudNavLink Match="NavLinkMatch.Prefix"
                                Href="/discount-categories"
                                Icon="@Icons.Material.Filled.Category">
                        دسته‌بندی‌ها
                    </MudNavLink>
                    <MudNavLink Match="NavLinkMatch.Prefix"
                                Href="/discount-orders"
                                Icon="@Icons.Material.Filled.ShoppingCart">
                        سفارشات و گزارش
                    </MudNavLink>
                </MudNavGroup>
            }
        </Authorized>
    </AuthorizeView>

    <MudDivider Class="my-2" />
    <MudText Class="nav-menu__title" Typo="Typo.subtitle2">مدیریت</MudText>

    <AuthorizeView Roles="Administrator">
        <Authorized>
            @if (CanManageUsers)
            {
                <MudNavLink Match="NavLinkMatch.Prefix"
                            Href="@(RouteConstance.UserPage)"
                            Icon="@Icons.Material.Filled.People">
                    کاربران
                </MudNavLink>
            }

            @if (CanManageRoles)
            {
                <MudNavLink Match="NavLinkMatch.Prefix"
                            Href="@(RouteConstance.Role)"
                            Icon="@Icons.Material.Filled.AdminPanelSettings">
                    نقش‌ها
                </MudNavLink>
            }

            @if (CanManagePayments)
            {
                <MudNavLink Match="NavLinkMatch.Prefix"
                            Href="/payment/manual-payments"
                            Icon="@Icons.Material.Filled.Payment">
                    پرداخت‌های دستی
                </MudNavLink>
            }

            <MudNavLink Match="NavLinkMatch.Prefix"
                        Href="/wallets"
                        Icon="@Icons.Material.Filled.AccountBalanceWallet">
                کیف‌پول کاربران
            </MudNavLink>

            <MudNavLink Match="NavLinkMatch.Prefix"
                        Href="/contracts"
                        Icon="@Icons.Material.Filled.Description">
                قراردادها
            </MudNavLink>
        </Authorized>
    </AuthorizeView>

    <MudDivider Class="my-2" />
    <MudText Class="nav-menu__title" Typo="Typo.subtitle2">مدیریت محتوا</MudText>

    <AuthorizeView Roles="Administrator">
        <Authorized>
            @if (CanManageBlog)
            {
                <MudNavLink Match="NavLinkMatch.Prefix"
                            Href="/blog/posts"
                            Icon="@Icons.Material.Filled.Article">
                    مدیریت بلاگ
                </MudNavLink>
            }

            @if (CanManageSitePages)
            {
                <MudNavLink Match="NavLinkMatch.Prefix"
                            Href="/content/page-settings"
                            Icon="@Icons.Material.Filled.WebAsset">
                    تنظیمات صفحات
                </MudNavLink>
            }

            @if (CanManageTags)
            {
                <MudNavLink Match="NavLinkMatch.Prefix"
                            Href="/tags"
                            Icon="@Icons.Material.Filled.Label">
                    مدیریت تگ‌ها
                </MudNavLink>
            }

            @if (CanManagePublicMessages)
            {
                <MudNavLink Match="NavLinkMatch.Prefix"
                            Href="/public-messages"
                            Icon="@Icons.Material.Filled.Campaign">
                    پیام‌های عمومی
                </MudNavLink>
            }
        </Authorized>
    </AuthorizeView>

    <MudDivider Class="my-2" />
    <MudText Class="nav-menu__title" Typo="Typo.subtitle2">سیستم</MudText>

    <AuthorizeView Roles="Administrator">
        <Authorized>
            @if (CanManageSystemConfiguration)
            {
                <MudNavLink Match="NavLinkMatch.Prefix"
                            Href="/system/configuration"
                            Icon="@Icons.Material.Filled.Tune">
                    مدیریت سیستم
                </MudNavLink>
            }

            @if (CanViewSettings)
            {
                <MudNavLink Match="NavLinkMatch.Prefix"
                            Href="/settings/app-versions"
                            Icon="@Icons.Material.Filled.PhoneAndroid">
                    نسخه اپلیکیشن‌ها
                </MudNavLink>
            }
        </Authorized>
    </AuthorizeView>

    <MudDivider Class="my-2" />

    <MudNavLink Match="NavLinkMatch.Prefix"
                Href="/settings"
                Icon="@Icons.Material.Filled.Settings">
        تنظیمات
    </MudNavLink>
</MudNavMenu>


@code {
    private bool _initialized;
    private int _pendingWithdrawalsCount;
    private bool CanViewDashboard;
    private bool CanManagePackages;
    private bool CanManageProducts;
    private bool CanViewOrders;
    private bool CanManageCategories;
    private bool CanManageTags;
    private bool CanManageUsers;
    private bool CanManageRoles;
    private bool CanManagePayments;
    private bool CanManageDiscountShop;
    private bool CanManagePublicMessages;
    private bool CanManageBlog;
    private bool CanManageSitePages;
    private bool CanViewSystemAlerts;
    private bool CanViewSystemHealth;
    private bool CanManageSystemConfiguration;
    private bool CanViewSettings;

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

    private async Task InitializePermissionsAsync()
    {
        if (_initialized)
        {
            return;
        }

        // Check if user is actually authenticated before doing anything
        var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
        var user = authState.User;
        if (user?.Identity == null || !user.Identity.IsAuthenticated)
        {
            return;
        }

        CanViewDashboard = await AuthorizationService.HasPermissionAsync("dashboard.view");

        CanManagePackages = await AuthorizationService.HasPermissionAsync("packages.manage");
        CanManageProducts = await AuthorizationService.HasPermissionAsync("products.view");
        CanViewOrders = await AuthorizationService.HasPermissionAsync("orders.view");
        CanManageCategories = await AuthorizationService.HasPermissionAsync("categories.manage");
        CanManageTags = await AuthorizationService.HasPermissionAsync("tags.manage");
        CanManageUsers = await AuthorizationService.HasPermissionAsync("users.view");
        CanManageRoles = await AuthorizationService.HasPermissionAsync("roles.manage");
        CanManagePayments = await AuthorizationService.HasPermissionAsync("manualpayments.create");
        CanManageDiscountShop = await AuthorizationService.HasPermissionAsync("discountshop.manage");
        CanManagePublicMessages = await AuthorizationService.HasPermissionAsync("publicmessages.view");
        CanManageBlog = await AuthorizationService.HasPermissionAsync("blog.manage");
        CanManageSitePages = await AuthorizationService.HasPermissionAsync("sitepages.manage");
        CanViewSystemAlerts = await AuthorizationService.HasPermissionAsync("system.alerts.view");
        CanViewSystemHealth = await AuthorizationService.HasPermissionAsync("system.health.view");
        CanManageSystemConfiguration = await AuthorizationService.HasPermissionAsync("settings.manage_configuration");
        CanViewSettings = await AuthorizationService.HasPermissionAsync("settings.view");

        _initialized = true;
        StateHasChanged();

        // Load pending badge only after confirmed authenticated
        _ = LoadPendingWithdrawalsCountAsync();
    }

    private async Task LoadPendingWithdrawalsCountAsync()
    {
        try
        {
            var request = new GetWithdrawalRequestsRequest
            {
                PageIndex = 1,
                PageSize = 1,
                Status = 0 // Pending
            };
            var result = await CommissionClient.GetWithdrawalRequestsAsync(request);
            _pendingWithdrawalsCount = result?.MetaData != null ? (int)result.MetaData.TotalCount : 0;
            StateHasChanged();
        }
        catch
        {
            // Silently ignore — NavMenu should never crash
        }
    }
}
