using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Caching.Memory;
using OnlyOneAccessTemplate.Services;
using OnlyOneAccessTemplate.Models;

namespace OnlyOneAccessTemplate.Controllers
{
    
    public abstract class BaseController : Controller
    {
        protected readonly ISiteConfigurationService _siteConfig;
        protected readonly ILanguageService _languageService;
        protected readonly ISeoService _seoService;
        protected readonly IMemoryCache _cache;
        protected readonly IConfiguration _configuration;

        public BaseController(
            ISiteConfigurationService siteConfig,
            ILanguageService languageService,
            ISeoService seoService,
            IMemoryCache cache,
            IConfiguration configuration)
        {
            _siteConfig = siteConfig;
            _languageService = languageService;
            _seoService = seoService;
            _cache = cache;
            _configuration = configuration;
        }

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var language = GetCurrentLanguage();
            var config = _siteConfig.GetConfiguration(language);
            var currentUrl = GetCurrentUrl();

            SetupSeoViewBag(config, language, currentUrl);
            SetupContentViewBag(config, language);
            base.OnActionExecuting(context);
        }

        protected virtual string GetCurrentLanguage()
        {
            var path = Request.Path.Value ?? "";

            if (path.StartsWith("/en"))
                return "en";
            if (path.StartsWith("/es"))
                return "es";

            return "pt"; // default
        }

        protected string GetCurrentUrl()
        {
            return $"{Request.Scheme}://{Request.Host}{Request.Path}{Request.QueryString}";
        }

        protected void SetupSeoViewBag(SiteConfiguration config, string language, string currentUrl)
        {
            // Basic SEO
            ViewBag.Language = language;
            ViewBag.Direction = _languageService.GetLanguageDirection(language);
            ViewBag.SiteName = config.Seo.SiteName;
            ViewBag.SiteDescription = config.Seo.DefaultDescription;
            ViewBag.CanonicalUrl = currentUrl;
            ViewBag.Author = config.Seo.Author;
            ViewBag.GTMId = config.Seo.GoogleTagManagerId;

            // Default SEO values
            ViewBag.Title = ViewBag.Title ?? config.Seo.DefaultTitle;
            ViewBag.Description = ViewBag.Description ?? config.Seo.DefaultDescription;
            ViewBag.Keywords = ViewBag.Keywords ?? config.Seo.DefaultKeywords;

            // Open Graph
            ViewBag.OgTitle = ViewBag.Title;
            ViewBag.OgDescription = ViewBag.Description;
            ViewBag.OgImage = config.Seo.OgImage;
            ViewBag.OgLocale = GetOgLocale(language);
            ViewBag.TwitterHandle = config.Seo.TwitterHandle;

            // Language alternatives
            SetupHreflangUrls(currentUrl, language);

            // Current language display
            ViewBag.CurrentLanguageDisplay = _languageService.GetLanguageDisplayName(language);
        }

        protected void SetupContentViewBag(SiteConfiguration config, string language)
        {
            // Navigation
            ViewBag.HomeUrl = language == "pt" ? "/" : $"/{language}";
            ViewBag.AboutUrl = language == "pt" ? "/about" : $"/{language}/about";
            ViewBag.ContactUrl = language == "pt" ? "/contact" : $"/{language}/contact";
            ViewBag.PrivacyUrl = language == "pt" ? "/privacy" : $"/{language}/privacy";
            ViewBag.TermsUrl = language == "pt" ? "/terms" : $"/{language}/terms";

            // Menu texts based on language
            switch (language)
            {
                case "en":
                    SetupEnglishContent();
                    break;
                case "es":
                    SetupSpanishContent();
                    break;
                default:
                    SetupPortugueseContent();
                    break;
            }

            // Logo and branding
            ViewBag.LogoUrl = "/img/logo.png";
            ViewBag.BodyClass = $"lang-{language}";

            // Conversion config
            ViewBag.ConversionConfig = config.Conversion;
        }

        protected void SetupPortugueseContent()
        {
            // Menu
            ViewBag.MenuHome = "Início";
            ViewBag.MenuAbout = "Sobre";
            ViewBag.MenuContact = "Contato";
            ViewBag.MenuPrivacy = "Privacidade";
            ViewBag.MenuTerms = "Termos";

            // Hero Section
            ViewBag.DefaultHeroTitle = "Transforme Seu Negócio com Nossa Solução";
            ViewBag.DefaultHeroSubtitle = "Aumente suas vendas em até 300% com nossa metodologia comprovada e suporte especializado.";
            ViewBag.DefaultCtaText = "Comece Agora";
            ViewBag.WatchVideoText = "Assistir Vídeo";

            // Features
            ViewBag.DefaultFeaturesTitle = "Por Que Escolher Nossa Solução?";
            ViewBag.DefaultFeaturesSubtitle = "Descubra os benefícios que já transformaram mais de 1000 empresas";
            ViewBag.Feature1Title = "Resultados Rápidos";
            ViewBag.Feature1Description = "Veja os primeiros resultados em até 30 dias";
            ViewBag.Feature2Title = "Suporte 24/7";
            ViewBag.Feature2Description = "Equipe especializada sempre disponível";
            ViewBag.Feature3Title = "Metodologia Comprovada";
            ViewBag.Feature3Description = "Mais de 1000 casos de sucesso documentados";

            // Form
            ViewBag.FormTitle = "Solicite uma Demonstração Gratuita";
            ViewBag.FormSubtitle = "Preencha o formulário e nossa equipe entrará em contato";
            ViewBag.NameLabel = "Nome Completo";
            ViewBag.NamePlaceholder = "Digite seu nome completo";
            ViewBag.EmailLabel = "E-mail";
            ViewBag.EmailPlaceholder = "Digite seu e-mail";
            ViewBag.PhoneLabel = "Telefone";
            ViewBag.PhonePlaceholder = "Digite seu telefone";
            ViewBag.SubmitButtonText = "Solicitar Demonstração";
            ViewBag.LoadingText = "Enviando...";

            // Quick Form
            ViewBag.QuickFormTitle = "Acesso Rápido";
            ViewBag.QuickSubmitText = "Começar Agora";
            ViewBag.QuickConsentText = "Concordo em receber informações por e-mail";

            // Validation
            ViewBag.RequiredFieldMessage = "Este campo é obrigatório";
            ViewBag.EmailValidationMessage = "Digite um e-mail válido";
            ViewBag.PhoneValidationMessage = "Digite um telefone válido";
            ViewBag.ConsentValidationMessage = "Você deve concordar para continuar";

            // Consent
            ViewBag.ConsentText = "Concordo em receber comunicações e com a <a href='/privacy'>Política de Privacidade</a>";

            // Benefits
            ViewBag.BenefitsTitle = "O que você vai receber:";
            ViewBag.DefaultBenefit1 = "Consultoria personalizada";
            ViewBag.DefaultBenefit2 = "Suporte técnico especializado";
            ViewBag.DefaultBenefit3 = "Garantia de resultados";

            // Testimonials
            ViewBag.DefaultTestimonialsTitle = "O Que Nossos Clientes Dizem";
            ViewBag.DefaultTestimonialsSubtitle = "Mais de 1000 empresas já transformaram seus resultados";
            SetupPortugueseTestimonials();

            // CTA
            ViewBag.DefaultCtaTitle = "Pronto para Transformar Seu Negócio?";
            ViewBag.DefaultCtaSubtitle = "Junte-se a mais de 1000 empresas que já alcançaram resultados extraordinários";
            ViewBag.DefaultCtaButtonText = "Começar Transformação";

            // Footer
            ViewBag.FooterDescription = "Transformando negócios através de soluções inovadoras";
            ViewBag.FooterMenuTitle = "Links";
            ViewBag.FooterLegalTitle = "Legal";
            ViewBag.FooterContactTitle = "Contato";
            ViewBag.FooterCopyright = "Todos os direitos reservados.";
            ViewBag.FooterMadeWith = "Feito com ❤️ no Brasil";

            // Success
            ViewBag.SuccessTitle = "Obrigado!";
            ViewBag.SuccessMessage = "Recebemos sua solicitação. Nossa equipe entrará em contato em breve.";
            ViewBag.CloseButtonText = "Fechar";

            // Thank You Page
            ViewBag.NextStepsTitle = "O que acontece agora?";
            ViewBag.Step1Title = "Análise";
            ViewBag.Step1Description = "Nossa equipe analisará sua solicitação";
            ViewBag.Step2Title = "Contato";
            ViewBag.Step2Description = "Entraremos em contato em até 24h";
            ViewBag.Step3Title = "Implementação";
            ViewBag.Step3Description = "Iniciaremos sua transformação";
            ViewBag.ContactInfoTitle = "Precisa falar conosco?";
            ViewBag.BackToHomeText = "Voltar ao Início";
            ViewBag.WhatsAppText = "Falar no WhatsApp";
            ViewBag.RedirectConfirmText = "Deseja voltar à página inicial?";

            // Security
            ViewBag.SecurityText = "Seus dados estão seguros conosco";

            // Time
            ViewBag.DaysText = "Dias";
            ViewBag.HoursText = "Horas";
            ViewBag.MinutesText = "Min";
            ViewBag.SecondsText = "Seg";

            // Contact info
            ViewBag.ContactEmail = "contato@seusite.com";
            ViewBag.ContactPhone = "(11) 99999-9999";
            ViewBag.ContactAddress = "São Paulo, SP";
            ViewBag.TestimonialsCount = "Mais de 500 avaliações 5 estrelas";
        }

        protected void SetupEnglishContent()
        {
            // Menu
            ViewBag.MenuHome = "Home";
            ViewBag.MenuAbout = "About";
            ViewBag.MenuContact = "Contact";
            ViewBag.MenuPrivacy = "Privacy";
            ViewBag.MenuTerms = "Terms";

            // Hero Section
            ViewBag.DefaultHeroTitle = "Transform Your Business with Our Solution";
            ViewBag.DefaultHeroSubtitle = "Increase your sales by up to 300% with our proven methodology and expert support.";
            ViewBag.DefaultCtaText = "Get Started";
            ViewBag.WatchVideoText = "Watch Video";

            // Features
            ViewBag.DefaultFeaturesTitle = "Why Choose Our Solution?";
            ViewBag.DefaultFeaturesSubtitle = "Discover the benefits that have already transformed over 1000 companies";
            ViewBag.Feature1Title = "Fast Results";
            ViewBag.Feature1Description = "See first results within 30 days";
            ViewBag.Feature2Title = "24/7 Support";
            ViewBag.Feature2Description = "Specialized team always available";
            ViewBag.Feature3Title = "Proven Method";
            ViewBag.Feature3Description = "Over 1000 documented success cases";

            // Form
            ViewBag.FormTitle = "Request a Free Demo";
            ViewBag.FormSubtitle = "Fill out the form and our team will contact you";
            ViewBag.NameLabel = "Full Name";
            ViewBag.NamePlaceholder = "Enter your full name";
            ViewBag.EmailLabel = "Email";
            ViewBag.EmailPlaceholder = "Enter your email";
            ViewBag.PhoneLabel = "Phone";
            ViewBag.PhonePlaceholder = "Enter your phone";
            ViewBag.SubmitButtonText = "Request Demo";
            ViewBag.LoadingText = "Sending...";

            // Quick Form
            ViewBag.QuickFormTitle = "Quick Access";
            ViewBag.QuickSubmitText = "Start Now";
            ViewBag.QuickConsentText = "I agree to receive information by email";

            // Validation
            ViewBag.RequiredFieldMessage = "This field is required";
            ViewBag.EmailValidationMessage = "Enter a valid email";
            ViewBag.PhoneValidationMessage = "Enter a valid phone";
            ViewBag.ConsentValidationMessage = "You must agree to continue";

            // Consent
            ViewBag.ConsentText = "I agree to receive communications and with the <a href='/en/privacy'>Privacy Policy</a>";

            // Benefits
            ViewBag.BenefitsTitle = "What you'll receive:";
            ViewBag.DefaultBenefit1 = "Personalized consultation";
            ViewBag.DefaultBenefit2 = "Specialized technical support";
            ViewBag.DefaultBenefit3 = "Results guarantee";

            // Testimonials
            ViewBag.DefaultTestimonialsTitle = "What Our Clients Say";
            ViewBag.DefaultTestimonialsSubtitle = "Over 1000 companies have already transformed their results";
            SetupEnglishTestimonials();

            // CTA
            ViewBag.DefaultCtaTitle = "Ready to Transform Your Business?";
            ViewBag.DefaultCtaSubtitle = "Join over 1000 companies that have already achieved extraordinary results";
            ViewBag.DefaultCtaButtonText = "Start Transformation";

            // Footer
            ViewBag.FooterDescription = "Transforming businesses through innovative solutions";
            ViewBag.FooterMenuTitle = "Links";
            ViewBag.FooterLegalTitle = "Legal";
            ViewBag.FooterContactTitle = "Contact";
            ViewBag.FooterCopyright = "All rights reserved.";
            ViewBag.FooterMadeWith = "Made with ❤️ in Brazil";

            // Success
            ViewBag.SuccessTitle = "Thank You!";
            ViewBag.SuccessMessage = "We received your request. Our team will contact you soon.";
            ViewBag.CloseButtonText = "Close";

            // Thank You Page
            ViewBag.NextStepsTitle = "What happens next?";
            ViewBag.Step1Title = "Analysis";
            ViewBag.Step1Description = "Our team will analyze your request";
            ViewBag.Step2Title = "Contact";
            ViewBag.Step2Description = "We'll contact you within 24h";
            ViewBag.Step3Title = "Implementation";
            ViewBag.Step3Description = "We'll start your transformation";
            ViewBag.ContactInfoTitle = "Need to talk to us?";
            ViewBag.BackToHomeText = "Back to Home";
            ViewBag.WhatsAppText = "Chat on WhatsApp";
            ViewBag.RedirectConfirmText = "Would you like to return to the home page?";

            // Security
            ViewBag.SecurityText = "Your data is safe with us";

            // Time
            ViewBag.DaysText = "Days";
            ViewBag.HoursText = "Hours";
            ViewBag.MinutesText = "Min";
            ViewBag.SecondsText = "Sec";

            // Contact info
            ViewBag.ContactEmail = "contact@yoursite.com";
            ViewBag.ContactPhone = "+1 (555) 123-4567";
            ViewBag.ContactAddress = "New York, NY";
            ViewBag.TestimonialsCount = "Over 500 five-star reviews";
        }

        protected void SetupSpanishContent()
        {
            // Menu
            ViewBag.MenuHome = "Inicio";
            ViewBag.MenuAbout = "Acerca";
            ViewBag.MenuContact = "Contacto";
            ViewBag.MenuPrivacy = "Privacidad";
            ViewBag.MenuTerms = "Términos";

            // Hero Section
            ViewBag.DefaultHeroTitle = "Transforma Tu Negocio con Nuestra Solución";
            ViewBag.DefaultHeroSubtitle = "Aumenta tus ventas hasta un 300% con nuestra metodología probada y soporte especializado.";
            ViewBag.DefaultCtaText = "Comenzar Ahora";
            ViewBag.WatchVideoText = "Ver Video";

            // Features
            ViewBag.DefaultFeaturesTitle = "¿Por Qué Elegir Nuestra Solución?";
            ViewBag.DefaultFeaturesSubtitle = "Descubre los beneficios que ya han transformado más de 1000 empresas";
            ViewBag.Feature1Title = "Resultados Rápidos";
            ViewBag.Feature1Description = "Ve los primeros resultados en 30 días";
            ViewBag.Feature2Title = "Soporte 24/7";
            ViewBag.Feature2Description = "Equipo especializado siempre disponible";
            ViewBag.Feature3Title = "Metodología Probada";
            ViewBag.Feature3Description = "Más de 1000 casos de éxito documentados";

            // Form
            ViewBag.FormTitle = "Solicita una Demo Gratuita";
            ViewBag.FormSubtitle = "Completa el formulario y nuestro equipo te contactará";
            ViewBag.NameLabel = "Nombre Completo";
            ViewBag.NamePlaceholder = "Ingresa tu nombre completo";
            ViewBag.EmailLabel = "Correo";
            ViewBag.EmailPlaceholder = "Ingresa tu correo";
            ViewBag.PhoneLabel = "Teléfono";
            ViewBag.PhonePlaceholder = "Ingresa tu teléfono";
            ViewBag.SubmitButtonText = "Solicitar Demo";
            ViewBag.LoadingText = "Enviando...";

            // Quick Form
            ViewBag.QuickFormTitle = "Acceso Rápido";
            ViewBag.QuickSubmitText = "Comenzar Ahora";
            ViewBag.QuickConsentText = "Acepto recibir información por correo";

            // Validation
            ViewBag.RequiredFieldMessage = "Este campo es obligatorio";
            ViewBag.EmailValidationMessage = "Ingresa un correo válido";
            ViewBag.PhoneValidationMessage = "Ingresa un teléfono válido";
            ViewBag.ConsentValidationMessage = "Debes aceptar para continuar";

            // Consent
            ViewBag.ConsentText = "Acepto recibir comunicaciones y la <a href='/es/privacy'>Política de Privacidad</a>";

            // Benefits
            ViewBag.BenefitsTitle = "Lo que recibirás:";
            ViewBag.DefaultBenefit1 = "Consultoría personalizada";
            ViewBag.DefaultBenefit2 = "Soporte técnico especializado";
            ViewBag.DefaultBenefit3 = "Garantía de resultados";

            // Testimonials
            ViewBag.DefaultTestimonialsTitle = "Lo Que Dicen Nuestros Clientes";
            ViewBag.DefaultTestimonialsSubtitle = "Más de 1000 empresas ya han transformado sus resultados";
            SetupSpanishTestimonials();

            // CTA
            ViewBag.DefaultCtaTitle = "¿Listo para Transformar Tu Negocio?";
            ViewBag.DefaultCtaSubtitle = "Únete a más de 1000 empresas que ya han logrado resultados extraordinarios";
            ViewBag.DefaultCtaButtonText = "Comenzar Transformación";

            // Footer
            ViewBag.FooterDescription = "Transformando negocios a través de soluciones innovadoras";
            ViewBag.FooterMenuTitle = "Enlaces";
            ViewBag.FooterLegalTitle = "Legal";
            ViewBag.FooterContactTitle = "Contacto";
            ViewBag.FooterCopyright = "Todos los derechos reservados.";
            ViewBag.FooterMadeWith = "Hecho con ❤️ en Brasil";

            // Success
            ViewBag.SuccessTitle = "¡Gracias!";
            ViewBag.SuccessMessage = "Recibimos tu solicitud. Nuestro equipo te contactará pronto.";
            ViewBag.CloseButtonText = "Cerrar";

            // Thank You Page
            ViewBag.NextStepsTitle = "¿Qué pasa ahora?";
            ViewBag.Step1Title = "Análisis";
            ViewBag.Step1Description = "Nuestro equipo analizará tu solicitud";
            ViewBag.Step2Title = "Contacto";
            ViewBag.Step2Description = "Te contactaremos en 24h";
            ViewBag.Step3Title = "Implementación";
            ViewBag.Step3Description = "Comenzaremos tu transformación";
            ViewBag.ContactInfoTitle = "¿Necesitas hablar con nosotros?";
            ViewBag.BackToHomeText = "Volver al Inicio";
            ViewBag.WhatsAppText = "Hablar por WhatsApp";
            ViewBag.RedirectConfirmText = "¿Te gustaría volver a la página principal?";

            // Security
            ViewBag.SecurityText = "Tus datos están seguros con nosotros";

            // Time
            ViewBag.DaysText = "Días";
            ViewBag.HoursText = "Horas";
            ViewBag.MinutesText = "Min";
            ViewBag.SecondsText = "Seg";

            // Contact info
            ViewBag.ContactEmail = "contacto@tusitioweb.com";
            ViewBag.ContactPhone = "+34 123 456 789";
            ViewBag.ContactAddress = "Madrid, España";
            ViewBag.TestimonialsCount = "Más de 500 reseñas de 5 estrellas";
        }

        protected void SetupPortugueseTestimonials()
        {
            ViewBag.Testimonial1Quote = "Aumentamos nossas vendas em 250% em apenas 3 meses. Incrível!";
            ViewBag.Testimonial1Name = "Maria Silva";
            ViewBag.Testimonial1Position = "CEO, TechStart";

            ViewBag.Testimonial2Quote = "O suporte é excepcional. Sempre prontos a ajudar quando precisamos.";
            ViewBag.Testimonial2Name = "João Santos";
            ViewBag.Testimonial2Position = "Diretor, InovaCorp";

            ViewBag.Testimonial3Quote = "A metodologia realmente funciona. Resultados visíveis desde o primeiro mês.";
            ViewBag.Testimonial3Name = "Ana Costa";
            ViewBag.Testimonial3Position = "Gerente, GrowBiz";
        }

        protected void SetupEnglishTestimonials()
        {
            ViewBag.Testimonial1Quote = "We increased our sales by 250% in just 3 months. Amazing!";
            ViewBag.Testimonial1Name = "Mary Johnson";
            ViewBag.Testimonial1Position = "CEO, TechStart";

            ViewBag.Testimonial2Quote = "The support is exceptional. Always ready to help when we need it.";
            ViewBag.Testimonial2Name = "John Smith";
            ViewBag.Testimonial2Position = "Director, InovaCorp";

            ViewBag.Testimonial3Quote = "The methodology really works. Visible results from the first month.";
            ViewBag.Testimonial3Name = "Sarah Davis";
            ViewBag.Testimonial3Position = "Manager, GrowBiz";
        }

        protected void SetupSpanishTestimonials()
        {
            ViewBag.Testimonial1Quote = "Aumentamos nuestras ventas un 250% en solo 3 meses. ¡Increíble!";
            ViewBag.Testimonial1Name = "María García";
            ViewBag.Testimonial1Position = "CEO, TechStart";

            ViewBag.Testimonial2Quote = "El soporte es excepcional. Siempre listos para ayudar cuando lo necesitamos.";
            ViewBag.Testimonial2Name = "Carlos López";
            ViewBag.Testimonial2Position = "Director, InovaCorp";

            ViewBag.Testimonial3Quote = "La metodología realmente funciona. Resultados visibles desde el primer mes.";
            ViewBag.Testimonial3Name = "Ana Rodríguez";
            ViewBag.Testimonial3Position = "Gerente, GrowBiz";
        }

        protected void SetupHreflangUrls(string currentUrl, string currentLanguage)
        {
            var hreflangUrls = _languageService.GetHreflangUrls(currentUrl, currentLanguage);

            ViewBag.PtUrl = hreflangUrls.GetValueOrDefault("pt", "/");
            ViewBag.EnUrl = hreflangUrls.GetValueOrDefault("en", "/en");
            ViewBag.EsUrl = hreflangUrls.GetValueOrDefault("es", "/es");
            ViewBag.DefaultUrl = ViewBag.PtUrl;
        }

        protected string GetOgLocale(string language)
        {
            return language switch
            {
                "en" => "en_US",
                "es" => "es_ES",
                "pt" => "pt_BR",
                _ => "pt_BR"
            };
        }

        protected void SetPageSeo(string title, string description, string keywords = null, string ogImage = null)
        {
            ViewBag.Title = title;
            ViewBag.Description = description;
            ViewBag.Keywords = keywords;

            if (!string.IsNullOrEmpty(ogImage))
            {
                ViewBag.OgImage = ogImage;
            }
        }
    }
}
