using System.Diagnostics;
using System.Text;
using Microsoft.AspNetCore.Mvc;
using CarneiroTech.Models;
using CarneiroTech.Resources;
using CarneiroTech.Services;

namespace CarneiroTech.Controllers;

public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;
    private readonly ICaseService _caseService;
    private readonly ILanguageService _languageService;

    public HomeController(ILogger<HomeController> logger, ICaseService caseService, ILanguageService languageService)
    {
        _logger = logger;
        _caseService = caseService;
        _languageService = languageService;
    }

    public async Task<IActionResult> Index()
    {
        var featuredCases = await _caseService.GetFeaturedCasesAsync();
        var lang = _languageService.GetCurrentLanguage(HttpContext);

        ViewData["Title"] = SiteStrings.Get("home.seo.title", lang);
        ViewData["Description"] = SiteStrings.Get("home.seo.description", lang);
        ViewData["Keywords"] = SiteStrings.Get("home.seo.keywords", lang);

        return View(featuredCases);
    }

    public IActionResult Privacy()
    {
        var lang = _languageService.GetCurrentLanguage(HttpContext);
        ViewData["Title"] = SiteStrings.Get("privacy.title", lang);
        return View();
    }

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

    [Route("sitemap.xml")]
    public async Task<IActionResult> Sitemap()
    {
        var cases = await _caseService.GetAllCasesAsync();

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

        // Homepage
        sitemap.AppendLine($@"  <url>
    <loc>https://carneirotech.com/</loc>
    <lastmod>{DateTime.UtcNow:yyyy-MM-dd}</lastmod>
    <changefreq>weekly</changefreq>
    <priority>1.0</priority>
  </url>");

        // Cases index
        sitemap.AppendLine($@"  <url>
    <loc>https://carneirotech.com/cases</loc>
    <lastmod>{DateTime.UtcNow:yyyy-MM-dd}</lastmod>
    <changefreq>weekly</changefreq>
    <priority>0.9</priority>
  </url>");

        // Each case
        foreach (var c in cases)
        {
            var lastMod = c.Metadata.Date != DateTime.MinValue ? c.Metadata.Date : DateTime.UtcNow;
            sitemap.AppendLine($@"  <url>
    <loc>https://carneirotech.com/cases/{c.Metadata.Slug}</loc>
    <lastmod>{lastMod:yyyy-MM-dd}</lastmod>
    <changefreq>monthly</changefreq>
    <priority>0.8</priority>
  </url>");
        }

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

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

    [HttpPost]
    public IActionResult Contact(ContactFormModel model)
    {
        if (!ModelState.IsValid)
        {
            TempData["Error"] = "Por favor, preencha todos os campos corretamente.";
            return RedirectToAction("Index", new { fragment = "contact" });
        }

        // TODO: Implement email sending logic here (SendGrid, SMTP, etc.)
        _logger.LogInformation($"Contact form submitted: {model.Name} - {model.Email}");

        TempData["Success"] = "Mensagem enviada com sucesso! Retornaremos em breve.";
        return RedirectToAction("Index", new { fragment = "contact" });
    }
}
