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

namespace QRRapidoApp.Controllers
{
    [Authorize]
    public class PagamentoController : Controller
    {
        private readonly IPlanService _planService;
        private readonly AdDisplayService _adDisplayService;
        private readonly IUserService _userService;
        private readonly StripeService _stripeService;
        private readonly ILogger<PagamentoController> _logger;
        private readonly List<string> languages = new List<string> { "pt-BR", "es-PY", "es" };

        public PagamentoController(IPlanService planService, IUserService userService, StripeService stripeService, ILogger<PagamentoController> logger, AdDisplayService adDisplayService)
        {
            _planService = planService;
            _userService = userService;
            _stripeService = stripeService;
            _logger = logger;
            _adDisplayService = adDisplayService;
        }

        [HttpGet]
        public async Task<IActionResult> SelecaoPlano()
        {
            var plans = await _planService.GetActivePlansAsync();
            var countryCode = GetUserCountryCodeComplete(); // Implement this method based on your needs
            _adDisplayService.SetViewBagAds(ViewBag);

            var model = new SelecaoPlanoViewModel
            {
                Plans = plans,
                CountryCode = countryCode
            };

            return View(model);
        }

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

            var plan = await _planService.GetPlanByIdAsync(planId);
            if (plan == null)
            {
                return Json(new { success = false, error = "Plan not found" });
            }

            var countryCode = GetUserCountryCode();
            if (countryCode != lang && languages.Contains(lang))
            {
                countryCode = lang;
            }

            var priceId = plan.PricesByCountry.ContainsKey(countryCode) 
                ? plan.PricesByCountry[countryCode].StripePriceId 
                : plan.StripePriceId;

            try
            {
                var checkoutUrl = await _stripeService.CreateCheckoutSessionAsync(userId, priceId, lang);
                return Json(new { success = true, url = checkoutUrl });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"Error creating checkout session for user {userId} and plan {planId}");
                return Json(new { success = false, error = ex.Message });
            }
        }

        [HttpGet]
        public IActionResult Sucesso()
        {
            _adDisplayService.SetViewBagAds(ViewBag);
            ViewBag.SuccessMessage = "Pagamento concluído com sucesso! Bem-vindo ao Premium.";
            return View();
        }

        [HttpGet]
        public async Task<IActionResult> Cancelar()
        {
            _adDisplayService.SetViewBagAds(ViewBag);
            ViewBag.CancelMessage = "O pagamento foi cancelado. Você pode tentar novamente a qualquer momento.";

            var plans = await _planService.GetActivePlansAsync();
            var countryCode = GetUserCountryCode(); // Implement this method based on your needs
            _adDisplayService.SetViewBagAds(ViewBag);

            var model = new SelecaoPlanoViewModel
            {
                Plans = plans,
                CountryCode = countryCode
            };

            return View("SelecaoPlano", model);
        }

        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> StripeWebhook()
        {
            try
            {
                using var reader = new StreamReader(HttpContext.Request.Body);
                var json = await reader.ReadToEndAsync();
                var signature = Request.Headers["Stripe-Signature"].FirstOrDefault();

                if (string.IsNullOrEmpty(signature))
                {
                    return BadRequest("Missing Stripe signature");
                }

                await _stripeService.HandleWebhookAsync(json, signature);
                return Ok();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error processing Stripe webhook");
                return BadRequest(ex.Message);
            }
        }

        private string GetUserCountryCode()
        {
            // Check current culture from URL first
            var culture = HttpContext.Request.RouteValues["culture"]?.ToString() ??
                         HttpContext.Features.Get<Microsoft.AspNetCore.Localization.IRequestCultureFeature>()?.RequestCulture?.Culture?.Name;

            var countryMap = new Dictionary<string, string>
            {
                { "pt-BR", "BR" },
                { "es-PY", "PY" },
                { "es", "PY" }
            };

            if (!string.IsNullOrEmpty(culture) && countryMap.ContainsKey(culture))
            {
                return countryMap[culture];
            }

            // Fallback to Cloudflare header or default
            return HttpContext.Request.Headers["CF-IPCountry"].FirstOrDefault() ?? "BR";
        }
        private string GetUserCountryCodeComplete()
        {
            // Check current culture from URL first
            var culture = HttpContext.Request.RouteValues["culture"]?.ToString() ??
                         HttpContext.Features.Get<Microsoft.AspNetCore.Localization.IRequestCultureFeature>()?.RequestCulture?.Culture?.Name;

            if (languages.Contains(culture))
            {
                return culture;
            }

            // Fallback to Cloudflare header or default
            return HttpContext.Request.Headers["CF-IPCountry"].FirstOrDefault() ?? "BR";
        }
    }
}
