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

namespace FrontOffice.Main.Pages.Package;

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

    private UserPackageStatusDto? _userStatus;
    private MagicWalletStatus? _magicStatus;
    private bool _isLoading = true;
    private bool _canRepurchase = false;

    private List<BreadcrumbItem> _breadcrumbItems = new()
    {
        new BreadcrumbItem("صفحه اصلی", RouteConstants.Main.MainPage),
        new BreadcrumbItem("پروفایل", RouteConstants.Profile.Index),
        new BreadcrumbItem("پکیج‌های من", null, disabled: true)
    };

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

    private async Task LoadDataAsync()
    {
        _isLoading = true;

        try
        {
            _userStatus = await PackageService.GetUserPackageStatusAsync();

            if (_userStatus?.HasPurchasedPackage == true)
            {
                _magicStatus = await WalletService.GetMagicWalletStatusAsync();

                // Cycle complete: wallet back to Normal mode, at least one cycle done,
                // and deposit ceiling fully used (remaining = 0)
                _canRepurchase = _magicStatus != null
                    && _magicStatus.WalletMode == 0        // Normal mode
                    && _magicStatus.PurchaseCycleCount >= 1 // At least one cycle completed
                    && _magicStatus.MagicRemainingDeposit == 0; // Deposit ceiling used up
            }
        }
        catch (Exception ex)
        {
#if DEBUG
            Console.WriteLine($"Error loading user package status: {ex.Message}");
#endif
        }
        finally
        {
            _isLoading = false;
        }
    }

    private static string GetPurchaseMethodText(string? method)
    {
        return method switch
        {
            "DayaLoan" => "وام دایا",
            "DirectPurchase" => "پرداخت مستقیم",
            _ => "نامشخص"
        };
    }

    private static Color GetPurchaseMethodColor(string? method)
    {
        return method switch
        {
            "DayaLoan" => Color.Info,
            "DirectPurchase" => Color.Success,
            _ => Color.Default
        };
    }

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

    private int GetDepositProgress()
    {
        if (_magicStatus == null || _magicStatus.MagicMaxDeposit <= 0) return 0;
        var pct = (int)((_magicStatus.MagicTotalDeposited * 100) / _magicStatus.MagicMaxDeposit);
        return Math.Min(pct, 100);
    }
}
