using FrontOffice.Main.Utilities;
using CMSMicroservice.Protobuf.Protos.User;
using Microsoft.AspNetCore.Components;
using MudBlazor;

namespace FrontOffice.Main.Pages.Club.Components;

public partial class ActivationSection : ComponentBase
{
    [Inject] private ClubMembershipService ClubService { get; set; } = default!;
    [Inject] private AuthService AuthService { get; set; } = default!;
    [Inject] private UserContract.UserContractClient UserContract { get; set; } = default!;
    [Inject] private PackageService PackageService { get; set; } = default!;

    [Parameter] public EventCallback OnActivationSuccess { get; set; }

    private MudForm _form = default!;
    private bool _formIsValid;
    private bool _isSubmitting;
    private string? _errorMessage;

    private long _packageId = 1;
    private int _durationMonths = 1;
    private string? _activationCode;
    private long _basePackagePrice;

    protected override async Task OnInitializedAsync()
    {
        try
        {
            var packages = await PackageService.GetAllPackagesAsync();
            var basePackage = packages.FirstOrDefault(p => p.IsBasePackage) ?? packages.FirstOrDefault();
            _basePackagePrice = basePackage?.Price ?? 0;
        }
        catch { /* fallback to 0 */ }
    }

    private async Task HandleActivateAsync()
    {
        await _form.Validate();
        if (!_formIsValid)
            return;

        try
        {
            _isSubmitting = true;
            _errorMessage = null;

            var result = await ClubService.ActivateMembershipAsync(
                _packageId,
                _activationCode,
                _durationMonths
            );

            if (result.Success)
            {
                Snackbar.Add($"عضویت فعال شد! مبلغ پرداختی: {result.AmountPaid:N0} تومان", Severity.Success);
                
                // Refresh Token to update Claims (IsClubMemberActive, HasPurchasedPackage)
                try
                {
                    var userResponse = await UserContract.GetUserAsync(new());
                    await AuthService.InitUserAuthInfo();
                }
                catch
                {
                    // Token refresh failed but activation succeeded
                    Snackbar.Add("لطفاً مجدداً وارد شوید تا تغییرات اعمال شود.", Severity.Warning);
                }
                
                await OnActivationSuccess.InvokeAsync();
            }
            else
            {
                _errorMessage = result.Message ?? "خطا در فعال‌سازی عضویت";
            }
        }
        catch (Exception ex)
        {
            _errorMessage = $"خطا: {ex.Message}";
            Snackbar.Add(_errorMessage, Severity.Error);
        }
        finally
        {
            _isSubmitting = false;
        }
    }

    private string GetEstimatedCost()
    {
        if (_basePackagePrice <= 0) return "در حال بارگذاری...";
        var total = _basePackagePrice * _durationMonths;
        return $"{total:N0} تومان";
    }
}
