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

namespace FrontOffice.Main.Pages.Profile;

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

    private bool _isProcessing;
    private long _chargeAmount;
    private string? _paymentResult;
    private string? _pendingReturnUrl;
    private bool _isClubMemberActive;
    private bool _hasPurchasedPackage;
    private bool _authLoaded;
    private bool _redirectingToMagic;
    private bool _allowNormalDespiteMagic;
    private bool _needsMagicCeilingConsent;

    private readonly long[] _presetAmounts = { 500_000, 1_000_000, 5_000_000, 10_000_000, 20_000_000, 50_000_000 };

    [SupplyParameterFromQuery(Name = "payment")]
    public string? PaymentQueryParam { get; set; }

    [SupplyParameterFromQuery(Name = "amount")]
    public long? AmountQueryParam { get; set; }

    [SupplyParameterFromQuery(Name = "returnUrl")]
    public string? ReturnUrlQueryParam { get; set; }

    private bool ShowChargeForm =>
        _authLoaded
        && _isClubMemberActive
        && !_redirectingToMagic
        && (!_needsMagicCeilingConsent || _allowNormalDespiteMagic);

    protected override async Task OnInitializedAsync()
    {
        _paymentResult = PaymentQueryParam;

        if (AmountQueryParam is > 0)
            _chargeAmount = CreditChargeNavigation.NormalizeChargeAmount(AmountQueryParam.Value);

        if (CreditChargeNavigation.IsValidReturnUrl(ReturnUrlQueryParam))
            _pendingReturnUrl = ReturnUrlQueryParam;

        try
        {
            var userInfo = await AuthService.GetUserAuthInfo();
            _isClubMemberActive = userInfo.IsClubMemberActive;
            _hasPurchasedPackage = userInfo.HasPurchasedPackage;
        }
        catch
        {
            _isClubMemberActive = false;
            _hasPurchasedPackage = false;
        }
        finally
        {
            _authLoaded = true;
        }

        if (_isClubMemberActive)
            await EvaluateMagicWalletGateAsync();
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender && !string.IsNullOrEmpty(_pendingReturnUrl) && _isClubMemberActive && !_redirectingToMagic)
            await CreditChargeNavigation.SaveReturnUrlAsync(JSRuntime, _pendingReturnUrl);

        await base.OnAfterRenderAsync(firstRender);
    }

    private void AcceptMagicCeilingConsent()
    {
        _allowNormalDespiteMagic = true;
        _redirectingToMagic = false;
    }

    private void DeclineMagicCeilingConsent()
    {
        _redirectingToMagic = true;
        Navigation.NavigateTo(RouteConstants.Profile.MagicWallet);
    }

    private async Task StartCreditCharge()
    {
        if (!_isClubMemberActive)
        {
            Snackbar.Add(
                "برای شارژ کیف پول اصلی ابتدا باید پکیج را خریداری کرده و قرارداد باشگاه مشتریان را امضا کنید.",
                Severity.Warning);
            return;
        }

        if (await EvaluateMagicWalletGateAsync())
            return;

        if (_needsMagicCeilingConsent && !_allowNormalDespiteMagic)
            return;

        if (_chargeAmount <= 0 || _isProcessing) return;

        _isProcessing = true;
        StateHasChanged();

        try
        {
            if (!string.IsNullOrEmpty(_pendingReturnUrl))
                await CreditChargeNavigation.SaveReturnUrlAsync(JSRuntime, _pendingReturnUrl);
            else
            {
                var storedReturnUrl = await CreditChargeNavigation.GetReturnUrlAsync(JSRuntime);
                if (CreditChargeNavigation.IsValidReturnUrl(storedReturnUrl))
                    _pendingReturnUrl = storedReturnUrl;
            }

            var (success, gatewayUrl, error) = await WalletService.InitiateCreditChargeAsync(_chargeAmount);

            if (success && !string.IsNullOrEmpty(gatewayUrl))
            {
                Navigation.NavigateTo(gatewayUrl, forceLoad: true);
            }
            else
            {
                Snackbar.Add(error ?? "خطا در ایجاد درخواست پرداخت", Severity.Error);
            }
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا: {ex.Message}", Severity.Error);
        }
        finally
        {
            _isProcessing = false;
            StateHasChanged();
        }
    }

    /// <summary>
    /// Magic با ظرفیت باقی‌مانده → ریدایرکت به MagicWallet.
    /// Magic با سقف پر → نمایش تأیید روی صفحه برای شارژ ۱:۱.
    /// true یعنی مسیر شارژ فعلی باید متوقف شود.
    /// </summary>
    private async Task<bool> EvaluateMagicWalletGateAsync()
    {
        if (_allowNormalDespiteMagic)
            return false;

        try
        {
            var status = await WalletService.GetMagicWalletStatusAsync();
            if (status.WalletMode != 1)
            {
                _needsMagicCeilingConsent = false;
                return false;
            }

            if (status.MagicRemainingDeposit > 0)
            {
                var multiplier = status.MagicMultiplier > 0 ? status.MagicMultiplier : 2.5;
                var multiplierText = multiplier.ToString("0.#");

                _redirectingToMagic = true;
                _needsMagicCeilingConsent = false;
                Snackbar.Add(
                    $"کیف پول شما در حالت جادویی است. شارژ از این صفحه موجودی را چندبرابر نمی‌کند. برای دریافت ضریب جادویی (×{multiplierText}) به صفحه شارژ کیف پول جادویی هدایت می‌شوید.",
                    Severity.Info);

                Navigation.NavigateTo(RouteConstants.Profile.MagicWallet);
                return true;
            }

            _needsMagicCeilingConsent = true;
            return !_allowNormalDespiteMagic;
        }
        catch
        {
            // در صورت خطا در خواندن وضعیت، مانع شارژ عادی نشو
            return false;
        }
    }

    private async Task ContinueShoppingAsync()
    {
        var returnUrl = await CreditChargeNavigation.GetReturnUrlAsync(JSRuntime);
        await CreditChargeNavigation.ClearReturnUrlAsync(JSRuntime);

        if (CreditChargeNavigation.IsValidReturnUrl(returnUrl))
            Navigation.NavigateTo(returnUrl!);
    }

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