@page "/wallets"
@attribute [Authorize(Roles = "Administrator")]

@using CMSMicroservice.Protobuf.Protos.UserWallet
@using CMSMicroservice.Protobuf.Protos.UserWalletHistory
@using BackOffice.Pages.AutoComplete

@inject UserWalletContract.UserWalletContractClient WalletClient
@inject UserWalletHistoryContract.UserWalletHistoryContractClient ChangeLogClient

<div>
    <MudText Typo="Typo.h5" Class="mb-3">مدیریت کیف‌پول کاربران</MudText>

    <MudTabs Elevation="0" Rounded="true" Border="true" ApplyEffectsToContainer="true"
             PanelClass="pt-4" @bind-ActivePanelIndex="_activeTab">

        @* ── تب اول: لیست کیف‌پول‌ها ── *@
        <MudTabPanel Text="کیف‌پول‌ها" Icon="@Icons.Material.Filled.AccountBalanceWallet">
            <MudDataGrid T="GetAllUserWalletByFilterResponseModel" @ref="_walletGrid"
                         ServerData="LoadWallets"
                         Hover="true" Dense="true"
                         Height="calc(100vh - 300px)">
                <ToolBarContent>
                    <MudStack Row="true" Spacing="2" AlignItems="AlignItems.Center">
                        <UserAutoComplete Label="جستجوی کاربر" @bind-SelectedUserId="_filterUserId" />
                        <MudButton Variant="Variant.Filled" Color="Color.Primary"
                                   StartIcon="@Icons.Material.Filled.Search"
                                   OnClick="ApplyWalletFilter">جستجو</MudButton>
                    </MudStack>
                </ToolBarContent>
                <Columns>
                    <PropertyColumn Property="x => x.Id" Title="شناسه" />
                    <PropertyColumn Property="x => x.UserId" Title="کاربر">
                        <CellTemplate>
                            <MudStack Spacing="0">
                                <MudText Typo="Typo.body2"><strong>@context.Item.UserName</strong></MudText>
                                <MudText Typo="Typo.caption" Color="Color.Secondary">ID: @context.Item.UserId</MudText>
                            </MudStack>
                        </CellTemplate>
                    </PropertyColumn>
                    <TemplateColumn Title="موجودی اصلی">
                        <CellTemplate>
                            <MudText Color="Color.Primary"><strong>@context.Item.Balance.ToString("N0")</strong> تومان</MudText>
                        </CellTemplate>
                    </TemplateColumn>
                    <TemplateColumn Title="پاداش تیمی">
                        <CellTemplate>
                            <MudText Color="Color.Success">@context.Item.NetworkBalance.ToString("N0") تومان</MudText>
                        </CellTemplate>
                    </TemplateColumn>
                    <TemplateColumn Title="عملیات" Sortable="false">
                        <CellTemplate>
                            <MudTooltip Text="تاریخچه تغییرات">
                                <MudIconButton Icon="@Icons.Material.Filled.History"
                                               Size="Size.Small" Color="Color.Info"
                                               OnClick="@(() => ShowChangeLog(context.Item))" />
                            </MudTooltip>
                        </CellTemplate>
                    </TemplateColumn>
                </Columns>
                <NoRecordsContent>
                    <MudAlert Severity="Severity.Info" Dense="true" Variant="Variant.Text" Class="my-4">موردی یافت نشد.</MudAlert>
                </NoRecordsContent>
                <PagerContent>
                    <MudDataGridPager T="GetAllUserWalletByFilterResponseModel" PageSizeOptions="@(new int[] { 20, 50, 100 })"
                                      InfoFormat="سطر {first_item} تا {last_item} از {all_items}"
                                      RowsPerPageString="تعداد در صفحه" />
                </PagerContent>
            </MudDataGrid>
        </MudTabPanel>

        @* ── تب دوم: تاریخچه تغییرات ── *@
        <MudTabPanel Text="تاریخچه تغییرات" Icon="@Icons.Material.Filled.History">
            <MudStack Row="true" Spacing="2" AlignItems="AlignItems.Center" Class="mb-3">
                <UserAutoComplete Label="جستجوی کاربر" @bind-SelectedUserId="_logFilterUserId" />
                <MudSelect T="bool?" Clearable="true" Label="نوع تغییر"
                           Variant="Variant.Outlined" Margin="Margin.Dense"
                           @bind-Value="_logFilterIsIncrease" Style="max-width: 180px;">
                    <MudSelectItem T="bool?" Value="@((bool?)null)">همه</MudSelectItem>
                    <MudSelectItem T="bool?" Value="@((bool?)true)">افزایش</MudSelectItem>
                    <MudSelectItem T="bool?" Value="@((bool?)false)">کاهش</MudSelectItem>
                </MudSelect>
                <MudButton Variant="Variant.Filled" Color="Color.Primary"
                           StartIcon="@Icons.Material.Filled.Search"
                           OnClick="ApplyLogFilter">جستجو</MudButton>
            </MudStack>

            <MudDataGrid T="GetAllUserWalletHistoryByFilterResponseModel" @ref="_logGrid"
                         ServerData="LoadChangeLogs"
                         Hover="true" Dense="true"
                         Height="calc(100vh - 340px)">
                <Columns>
                    <PropertyColumn Property="x => x.Id" Title="شناسه" />
                    <PropertyColumn Property="x => x.WalletId" Title="کیف‌پول" />
                    <TemplateColumn Title="نوع">
                        <CellTemplate>
                            <MudChip T="string" Size="Size.Small"
                                     Color="@(context.Item.IsIncrease ? Color.Success : Color.Error)">
                                @(context.Item.IsIncrease ? "افزایش" : "کاهش")
                            </MudChip>
                        </CellTemplate>
                    </TemplateColumn>
                    <TemplateColumn Title="تغییر موجودی">
                        <CellTemplate>
                            <MudText>@context.Item.ChangeValue.ToString("N0")</MudText>
                        </CellTemplate>
                    </TemplateColumn>
                    <TemplateColumn Title="موجودی فعلی">
                        <CellTemplate>
                            <MudText Color="Color.Primary">@context.Item.CurrentBalance.ToString("N0")</MudText>
                        </CellTemplate>
                    </TemplateColumn>
                    <TemplateColumn Title="تغییر پاداش تیمی">
                        <CellTemplate>
                            <MudText>@context.Item.ChangeNerworkValue.ToString("N0")</MudText>
                        </CellTemplate>
                    </TemplateColumn>
                    <TemplateColumn Title="پاداش تیمی فعلی">
                        <CellTemplate>
                            <MudText Color="Color.Success">@context.Item.CurrentNetworkBalance.ToString("N0")</MudText>
                        </CellTemplate>
                    </TemplateColumn>
                    <TemplateColumn Title="شناسه مرجع">
                        <CellTemplate>
                            @(context.Item.RefrenceId?.ToString() ?? "—")
                        </CellTemplate>
                    </TemplateColumn>
                    <TemplateColumn Title="تاریخ">
                        <CellTemplate>
                            @context.Item.CreatedAt.ToDateTime().ToLocalTime().MiladiToJalaliWithTime()
                        </CellTemplate>
                    </TemplateColumn>
                </Columns>
                <NoRecordsContent>
                    <MudAlert Severity="Severity.Info" Dense="true" Variant="Variant.Text" Class="my-4">موردی یافت نشد.</MudAlert>
                </NoRecordsContent>
                <PagerContent>
                    <MudDataGridPager T="GetAllUserWalletHistoryByFilterResponseModel" PageSizeOptions="@(new int[] { 20, 50, 100 })"
                                      InfoFormat="سطر {first_item} تا {last_item} از {all_items}"
                                      RowsPerPageString="تعداد در صفحه" />
                </PagerContent>
            </MudDataGrid>
        </MudTabPanel>
    </MudTabs>
</div>

@code {
    private int _activeTab;
    private MudDataGrid<GetAllUserWalletByFilterResponseModel>? _walletGrid;
    private MudDataGrid<GetAllUserWalletHistoryByFilterResponseModel>? _logGrid;

    // Wallet filters
    private long? _filterUserId;

    // ChangeLog filters
    private long? _logFilterUserId;
    private bool? _logFilterIsIncrease;

    private async Task<GridData<GetAllUserWalletByFilterResponseModel>> LoadWallets(GridState<GetAllUserWalletByFilterResponseModel> state)
    {
        try
        {
            var request = new GetAllUserWalletByFilterRequest
            {
                PaginationState = new() { PageNumber = state.Page + 1, PageSize = state.PageSize },
                Filter = new GetAllUserWalletByFilterFilter()
            };

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

            var result = await WalletClient.GetAllUserWalletByFilterAsync(request);
            return new GridData<GetAllUserWalletByFilterResponseModel>
            {
                Items = result?.Models?.ToList() ?? new(),
                TotalItems = (int)(result?.MetaData?.TotalCount ?? 0)
            };
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا: {ex.Message}", Severity.Error);
            return new GridData<GetAllUserWalletByFilterResponseModel>();
        }
    }

    private async Task<GridData<GetAllUserWalletHistoryByFilterResponseModel>> LoadChangeLogs(GridState<GetAllUserWalletHistoryByFilterResponseModel> state)
    {
        try
        {
            var request = new GetAllUserWalletHistoryByFilterRequest
            {
                PaginationState = new() { PageNumber = state.Page + 1, PageSize = state.PageSize },
                Filter = new GetAllUserWalletHistoryByFilterFilter()
            };

            if (_logFilterUserId.HasValue && _logFilterUserId.Value > 0)
                request.Filter.UserId = _logFilterUserId.Value;

            if (_logFilterIsIncrease.HasValue)
                request.Filter.IsIncrease = _logFilterIsIncrease.Value;

            var result = await ChangeLogClient.GetAllUserWalletHistoryByFilterAsync(request);
            return new GridData<GetAllUserWalletHistoryByFilterResponseModel>
            {
                Items = result?.Models?.ToList() ?? new(),
                TotalItems = (int)(result?.MetaData?.TotalCount ?? 0)
            };
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا: {ex.Message}", Severity.Error);
            return new GridData<GetAllUserWalletHistoryByFilterResponseModel>();
        }
    }

    private async Task ApplyWalletFilter()
    {
        if (_walletGrid != null) await _walletGrid.ReloadServerData();
    }

    private async Task ApplyLogFilter()
    {
        if (_logGrid != null) await _logGrid.ReloadServerData();
    }

    private void ShowChangeLog(GetAllUserWalletByFilterResponseModel wallet)
    {
        _logFilterUserId = wallet.UserId;
        _activeTab = 1;
        StateHasChanged();
        _ = ApplyLogFilter();
    }
}
