using FrontOffice.Main.Utilities;
using Microsoft.AspNetCore.Components;
using MudBlazor;

namespace FrontOffice.Main.Pages.Profile;

public partial class Wallet : ComponentBase
{
    [Inject] private AuthService AuthService { get; set; } = default!;

    private (string Credit, string Discount, string Network) _balances = ("-", "-", "-");
    private List<WalletTransaction> _txs = new();
    private string? _filterReferenceId;
    private string _filterType = "all";
    private bool _isClubMemberActive;
    private bool _hasPurchasedPackage;
    private bool _isMagicWallet;
    private bool _magicCeilingFull;

    protected override async Task OnInitializedAsync()
    {
        try
        {
            var userInfo = await AuthService.GetUserAuthInfo();
            _isClubMemberActive = userInfo.IsClubMemberActive;
            _hasPurchasedPackage = userInfo.HasPurchasedPackage;
        }
        catch
        {
            _isClubMemberActive = false;
            _hasPurchasedPackage = false;
        }

        try
        {
            var magicStatus = await WalletService.GetMagicWalletStatusAsync();
            _isMagicWallet = magicStatus.WalletMode == 1;
            _magicCeilingFull = _isMagicWallet && magicStatus.MagicRemainingDeposit <= 0;
        }
        catch
        {
            _isMagicWallet = false;
            _magicCeilingFull = false;
        }

        var b = await WalletService.GetBalancesAsync();
        _balances = (FormatPrice(b.CreditBalance), FormatPrice(b.DiscountBalance), FormatPrice(b.NetworkBalance));
        _txs = await WalletService.GetTransactionsAsync();
    }

    private static string FormatPrice(long price) => string.Format("{0:N0} تومان", price);

    private async Task ApplyFilters()
    {
        long? refId = null;
        if (long.TryParse(_filterReferenceId, out var parsed) && parsed > 0)
        {
            refId = parsed;
        }
        bool? isIncrease = _filterType switch
        {
            "in" => true,
            "out" => false,
            _ => null
        };
        _txs = await WalletService.GetTransactionsAsync(refId, isIncrease);
    }
}
