using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using QRRapidoApp.Models.ViewModels;
using QRRapidoApp.Services;
using System.Security.Claims;

namespace QRRapidoApp.Controllers
{
    [Authorize]
    public class PremiumController : Controller
    {
        private readonly StripeService _stripeService;
        private readonly IUserService _userService;
        private readonly AdDisplayService _adDisplayService;
        private readonly IConfiguration _config;
        private readonly ILogger<PremiumController> _logger;

        public PremiumController(
                StripeService stripeService, 
                IUserService userService, 
                AdDisplayService adDisplayService, 
                IConfiguration config, 
                ILogger<PremiumController> logger)
        {
            _stripeService = stripeService;
            _userService = userService;
            _adDisplayService = adDisplayService;
            _config = config;
            _logger = logger;
        }

        [HttpGet]
        public IActionResult Upgrade()
        {
            _adDisplayService.SetViewBagAds(ViewBag);
            return RedirectToAction("SelecaoPlano", "Pagamento");
        }

        [HttpGet]
        public async Task<IActionResult> Dashboard()
        {
            _adDisplayService.SetViewBagAds(ViewBag);
            var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
            if (string.IsNullOrEmpty(userId))
            {
                return RedirectToAction("Login", "Account");
            }

            var user = await _userService.GetUserAsync(userId);
            if (user?.IsPremium != true)
            {
                return RedirectToAction("Upgrade");
            }

            var model = new PremiumDashboardViewModel
            {
                User = user,
                QRCodesThisMonth = await _userService.GetQRCountThisMonthAsync(userId),
                TotalQRCodes = user.QRHistoryIds?.Count ?? 0,
                SubscriptionStatus = await _stripeService.GetSubscriptionStatusAsync(user.StripeSubscriptionId),
                RecentQRCodes = await _userService.GetUserQRHistoryAsync(userId, 10)
            };

            // Calculate next billing date (simplified)
            if (user.PremiumExpiresAt.HasValue)
            {
                model.NextBillingDate = user.PremiumExpiresAt.Value.AddDays(-2); // Approximate
            }

            // QR type statistics
            model.QRTypeStats = model.RecentQRCodes
                .GroupBy(q => q.Type)
                .ToDictionary(g => g.Key, g => g.Count());

            return View(model);
        }

        [HttpPost]
        public async Task<IActionResult> CancelSubscription()
        {
            var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
            if (string.IsNullOrEmpty(userId))
            {
                return Json(new { success = false, error = "User not authenticated" });
            }

            try
            {
                var user = await _userService.GetUserAsync(userId);
                if (user?.StripeSubscriptionId == null)
                {
                    return Json(new { success = false, error = "No active subscription found" });
                }

                var success = await _stripeService.CancelSubscriptionAsync(user.StripeSubscriptionId);
                if (success)
                {
                    TempData["Success"] = "Assinatura cancelada com sucesso. Você manterá o acesso premium até o final do período pago.";
                    return Json(new { success = true });
                }
                else
                {
                    return Json(new { success = false, error = "Failed to cancel subscription" });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"Error canceling subscription for user {userId}");
                return Json(new { success = false, error = ex.Message });
            }
        }

        [HttpPost]
        public async Task<IActionResult> RequestRefund()
        {
            var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
            if (string.IsNullOrEmpty(userId))
            {
                return Json(new { success = false, error = "Usuário não autenticado" });
            }

            try
            {
                var (success, message) = await _stripeService.CancelAndRefundSubscriptionAsync(userId);

                if (success)
                {
                    TempData["Success"] = message;
                    return Json(new { success = true, message = message });
                }
                else
                {
                    return Json(new { success = false, error = message });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"Error processing refund for user {userId}");
                return Json(new { success = false, error = "Erro inesperado ao processar reembolso" });
            }
        }

        [HttpGet]
        public async Task<IActionResult> BillingPortal()
        {
            _adDisplayService.SetViewBagAds(ViewBag);
            var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
            if (string.IsNullOrEmpty(userId))
            {
                return RedirectToAction("Login", "Account");
            }

            try
            {
                // This would create a Stripe billing portal session
                // For now, redirect to dashboard
                return RedirectToAction("Dashboard");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"Error creating billing portal for user {userId}");
                return RedirectToAction("Dashboard");
            }
        }
    }
}