using Microsoft.AspNetCore.Mvc;
using QRRapidoApp.Models;
using QRRapidoApp.Services;
using System.Diagnostics;
using System.Security.Claims;
using Microsoft.Extensions.Localization;

namespace QRRapidoApp.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly AdDisplayService _adDisplayService;
        private readonly IUserService _userService;
        private readonly IConfiguration _config;
        private readonly IStringLocalizer<QRRapidoApp.Resources.SharedResource> _localizer;
        private readonly IMarkdownService _markdownService;

        public HomeController(
                                ILogger<HomeController> logger,
                                AdDisplayService adDisplayService,
                                IUserService userService,
                                IConfiguration config,
                                IStringLocalizer<QRRapidoApp.Resources.SharedResource> localizer,
                                IMarkdownService markdownService
                              )
        {
            _logger = logger;
            _adDisplayService = adDisplayService;
            _userService = userService;
            _config = config;
            _localizer = localizer;
            _markdownService = markdownService;
        }

        public async Task<IActionResult> Index()
        {
            var userId = User?.FindFirst(ClaimTypes.NameIdentifier)?.Value;
            
            ViewBag.ShowAds = await _adDisplayService.ShouldShowAds(userId);
            ViewBag.IsPremium = await _adDisplayService.HasValidPremiumSubscription(userId ?? "");
            ViewBag.IsAuthenticated = User.Identity?.IsAuthenticated ?? false;
            ViewBag.UserName = User.Identity?.Name ?? "";
            _adDisplayService.SetViewBagAds(ViewBag);

            // SEO and Analytics data
            ViewBag.Title = _config["App:TaglinePT"];
            ViewBag.Keywords = _config["SEO:KeywordsPT"];
            ViewBag.Description = _localizer["QRGenerateDescription"];

            // User stats for logged in users
            if (!string.IsNullOrEmpty(userId))
            {
                ViewBag.DailyQRCount = await _userService.GetDailyQRCountAsync(userId);
                ViewBag.MonthlyQRCount = await _userService.GetQRCountThisMonthAsync(userId);
            }

            return View();
        }

        public IActionResult Privacy()
        {
            var userId = User?.FindFirst(ClaimTypes.NameIdentifier)?.Value;
            
            ViewBag.ShowAds = _adDisplayService.ShouldShowAds(userId).Result;
            ViewBag.IsPremium = _adDisplayService.HasValidPremiumSubscription(userId ?? "").Result;
            ViewBag.IsAuthenticated = User.Identity?.IsAuthenticated ?? false;
            ViewBag.UserName = User.Identity?.Name ?? "";
            
            ViewBag.Title = _localizer["PrivacyPolicyTitle"];
            ViewBag.Description = _localizer["PrivacyPolicyDescription"];
            _adDisplayService.SetViewBagAds(ViewBag);

            return View();
        }

        public IActionResult Terms()
        {
            var userId = User?.FindFirst(ClaimTypes.NameIdentifier)?.Value;
            
            ViewBag.ShowAds = _adDisplayService.ShouldShowAds(userId).Result;
            ViewBag.IsPremium = _adDisplayService.HasValidPremiumSubscription(userId ?? "").Result;
            ViewBag.IsAuthenticated = User.Identity?.IsAuthenticated ?? false;
            ViewBag.UserName = User.Identity?.Name ?? "";
            
            ViewBag.Title = _localizer["TermsOfUseTitle"];
            ViewBag.Description = _localizer["TermsOfUseDescription"];
            _adDisplayService.SetViewBagAds(ViewBag);

            return View();
        }

        public IActionResult About()
        {
            var userId = User?.FindFirst(ClaimTypes.NameIdentifier)?.Value;
            
            ViewBag.ShowAds = _adDisplayService.ShouldShowAds(userId).Result;
            ViewBag.IsPremium = _adDisplayService.HasValidPremiumSubscription(userId ?? "").Result;
            ViewBag.IsAuthenticated = User.Identity?.IsAuthenticated ?? false;
            ViewBag.UserName = User.Identity?.Name ?? "";
            
            ViewBag.Title = _localizer["AboutPageTitle"];
            ViewBag.Description = _localizer["AboutPageDescription"];
            _adDisplayService.SetViewBagAds(ViewBag);

            return View();
        }

        public IActionResult Contact()
        {
            var userId = User?.FindFirst(ClaimTypes.NameIdentifier)?.Value;
            
            ViewBag.ShowAds = _adDisplayService.ShouldShowAds(userId).Result;
            ViewBag.IsPremium = _adDisplayService.HasValidPremiumSubscription(userId ?? "").Result;
            ViewBag.IsAuthenticated = User.Identity?.IsAuthenticated ?? false;
            ViewBag.UserName = User.Identity?.Name ?? "";
            
            ViewBag.Title = _localizer["ContactPageTitle"];
            ViewBag.Description = _localizer["ContactPageDescription"];
            _adDisplayService.SetViewBagAds(ViewBag);

            return View();
        }

        public IActionResult FAQ()
        {
            var userId = User?.FindFirst(ClaimTypes.NameIdentifier)?.Value;
            
            ViewBag.ShowAds = _adDisplayService.ShouldShowAds(userId).Result;
            ViewBag.IsPremium = _adDisplayService.HasValidPremiumSubscription(userId ?? "").Result;
            ViewBag.IsAuthenticated = User.Identity?.IsAuthenticated ?? false;
            ViewBag.UserName = User.Identity?.Name ?? "";
            
            ViewBag.Title = _localizer["FAQPageTitle"];
            ViewBag.Description = _localizer["FAQPageDescription"];
            _adDisplayService.SetViewBagAds(ViewBag);

            return View();
        }

        public IActionResult HowToUse()
        {
            var userId = User?.FindFirst(ClaimTypes.NameIdentifier)?.Value;
            
            ViewBag.ShowAds = _adDisplayService.ShouldShowAds(userId).Result;
            ViewBag.IsPremium = _adDisplayService.HasValidPremiumSubscription(userId ?? "").Result;
            ViewBag.IsAuthenticated = User.Identity?.IsAuthenticated ?? false;
            ViewBag.UserName = User.Identity?.Name ?? "";
            
            ViewBag.Title = _localizer["HowToUsePageTitle"];
            ViewBag.Description = _localizer["HowToUsePageDescription"];
            _adDisplayService.SetViewBagAds(ViewBag);

            return View();
        }

        //[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        //public IActionResult Error()
        //{
        //    return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        //}

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            var errorCode = Request.Query["code"].ToString();
            var errorMessage = "";

            // Interpretar c�digos de erro espec�ficos
            if (errorCode.StartsWith("M.C506"))
            {
                errorMessage = "Erro de autentica��o. Verifique suas credenciais e tente novamente.";
            }

            ViewBag.ErrorCode = errorCode;
            ViewBag.ErrorMessage = errorMessage;

            return View(new ErrorViewModel
            {
                RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier
            });
        }

        // Dynamic QR redirect endpoint
        [Route("d/{id}")]
        public async Task<IActionResult> DynamicRedirect(string id)
        {
            try
            {
                _adDisplayService.SetViewBagAds(ViewBag);
                // This would lookup the dynamic QR content from cache/database
                // For now, return a placeholder
                return Redirect("https://qrrapido.site");
            }
            catch
            {
                return NotFound();
            }
        }

        // Health check endpoint
        [Route("health")]
        public IActionResult Health()
        {
            return Ok(new { status = "healthy", timestamp = DateTime.UtcNow });
        }

        // Sitemap endpoint for SEO
        [Route("sitemap.xml")]
        public async Task<IActionResult> Sitemap()
        {
            var baseUrl = "https://qrrapido.site";
            var now = DateTime.UtcNow.ToString("yyyy-MM-dd");

            var sitemapBuilder = new System.Text.StringBuilder();
            sitemapBuilder.AppendLine(@"<?xml version=""1.0"" encoding=""UTF-8""?>");
            sitemapBuilder.AppendLine(@"<urlset xmlns=""http://www.sitemaps.org/schemas/sitemap/0.9"">");

            // Static pages
            sitemapBuilder.AppendLine($@"
                <url>
                    <loc>{baseUrl}/</loc>
                    <lastmod>{now}</lastmod>
                    <changefreq>daily</changefreq>
                    <priority>1.0</priority>
                </url>
                <url>
                    <loc>{baseUrl}/pt/</loc>
                    <lastmod>{now}</lastmod>
                    <changefreq>daily</changefreq>
                    <priority>0.9</priority>
                </url>
                <url>
                    <loc>{baseUrl}/es/</loc>
                    <lastmod>{now}</lastmod>
                    <changefreq>daily</changefreq>
                    <priority>0.9</priority>
                </url>
                <url>
                    <loc>{baseUrl}/pt-BR/About</loc>
                    <lastmod>{now}</lastmod>
                    <changefreq>monthly</changefreq>
                    <priority>0.8</priority>
                </url>
                <url>
                    <loc>{baseUrl}/es-PY/About</loc>
                    <lastmod>{now}</lastmod>
                    <changefreq>monthly</changefreq>
                    <priority>0.8</priority>
                </url>
                <url>
                    <loc>{baseUrl}/pt-BR/Contact</loc>
                    <lastmod>{now}</lastmod>
                    <changefreq>monthly</changefreq>
                    <priority>0.8</priority>
                </url>
                <url>
                    <loc>{baseUrl}/es-PY/Contact</loc>
                    <lastmod>{now}</lastmod>
                    <changefreq>monthly</changefreq>
                    <priority>0.8</priority>
                </url>
                <url>
                    <loc>{baseUrl}/pt-BR/FAQ</loc>
                    <lastmod>{now}</lastmod>
                    <changefreq>weekly</changefreq>
                    <priority>0.9</priority>
                </url>
                <url>
                    <loc>{baseUrl}/es-PY/FAQ</loc>
                    <lastmod>{now}</lastmod>
                    <changefreq>weekly</changefreq>
                    <priority>0.9</priority>
                </url>
                <url>
                    <loc>{baseUrl}/pt-BR/HowToUse</loc>
                    <lastmod>{now}</lastmod>
                    <changefreq>weekly</changefreq>
                    <priority>0.8</priority>
                </url>
                <url>
                    <loc>{baseUrl}/es-PY/HowToUse</loc>
                    <lastmod>{now}</lastmod>
                    <changefreq>weekly</changefreq>
                    <priority>0.8</priority>
                </url>
                <url>
                    <loc>{baseUrl}/Pagamento/SelecaoPlano</loc>
                    <lastmod>{now}</lastmod>
                    <changefreq>weekly</changefreq>
                    <priority>0.8</priority>
                </url>
                <url>
                    <loc>{baseUrl}/privacy</loc>
                    <lastmod>{now}</lastmod>
                    <changefreq>monthly</changefreq>
                    <priority>0.5</priority>
                </url>
                <url>
                    <loc>{baseUrl}/terms</loc>
                    <lastmod>{now}</lastmod>
                    <changefreq>monthly</changefreq>
                    <priority>0.5</priority>
                </url>");

            // Dynamic tutorial pages
            try
            {
                var allArticles = await _markdownService.GetAllArticlesForSitemapAsync();

                foreach (var article in allArticles)
                {
                    var slug = article.Title.ToLower().Replace(" ", "-");
                    var lastMod = article.LastMod.ToString("yyyy-MM-dd");

                    sitemapBuilder.AppendLine($@"
                <url>
                    <loc>{baseUrl}/{article.Culture}/tutoriais/{slug}</loc>
                    <lastmod>{lastMod}</lastmod>
                    <changefreq>weekly</changefreq>
                    <priority>0.8</priority>
                </url>");
                }

                _logger.LogInformation("Generated sitemap with {Count} tutorial articles", allArticles.Count);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error adding tutorials to sitemap");
            }

            sitemapBuilder.AppendLine("</urlset>");

            return Content(sitemapBuilder.ToString(), "application/xml");
        }
    }

    //public class ErrorViewModel
    //{
    //    public string? RequestId { get; set; }
    //    public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
    //}
}