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

namespace OnlyOneAccessTemplate.Controllers
{
    public 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);
            SetupConverterViewBag(language); // Nova configuração específica do conversor
            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)
        {
            ViewBag.GoogleAdsPublisher = _configuration.GetValue<string>("GoogleAds:PublisherID");
            ViewBag.GoogleAdsEnabled = _configuration.GetValue<bool>("GoogleAds:Enabled", true);

            // Basic SEO
            ViewBag.Language = language;
            ViewBag.Direction = _languageService.GetLanguageDirection(language);
            ViewBag.SiteName = config.SiteTitle;
            ViewBag.SiteDescription = config.SiteDescription;
            ViewBag.CanonicalUrl = currentUrl;
            ViewBag.Author = "Convert-it Online Team";
            ViewBag.GTMId = _configuration.GetValue<string>("SEO:GoogleTagManagerId");

            // Default SEO values
            ViewBag.Title = ViewBag.Title ?? config.SiteTitle;
            ViewBag.Description = ViewBag.Description ?? config.SiteDescription;
            ViewBag.Keywords = ViewBag.Keywords ?? config.SiteKeywords;

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

            // Language alternatives
            SetupHreflangUrls(currentUrl, language);

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

        protected void SetupContentViewBag(SiteConfiguration config, string language)
        {
            ViewBag.GoogleAdsPublisher = _configuration.GetValue<string>("GoogleAds:PublisherID");
            ViewBag.GoogleAdsEnabled = _configuration.GetValue<bool>("GoogleAds:Enabled", true);
            // 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}";

            // AdSense config
            ViewBag.AdSenseClientId = config.AdSenseClientId;
            ViewBag.AdSenseSlotId = config.AdSenseSlotId;
        }

        // Nova função para configurar textos específicos do conversor
        protected void SetupConverterViewBag(string language)
        {
            var converterType = _configuration.GetValue<string>("Converter:Type") ?? "generic";
            var converterName = _configuration.GetValue<string>("Converter:Name") ?? "Conversor Online";

            switch (language)
            {
                case "en":
                    SetupEnglishConverterContent(converterType, converterName);
                    break;
                case "es":
                    SetupSpanishConverterContent(converterType, converterName);
                    break;
                default:
                    SetupPortugueseConverterContent(converterType, converterName);
                    break;
            }
        }

        protected virtual void SetupPortugueseConverterContent(string converterType, string converterName)
        {
            // Configurações específicas por tipo de conversor
            switch (converterType)
            {
                case "text-case":
                    ViewBag.ConverterTitle = "CONVERSOR DE MAIÚSCULAS E MINÚSCULAS";
                    ViewBag.ConverterDescription = "Converta texto entre maiúsculas, minúsculas, título e primeira maiúscula";
                    ViewBag.Step1Title = "Cole o Texto";
                    ViewBag.Step1Description = "Digite ou cole o texto que deseja converter";
                    ViewBag.Step2Title = "Escolha o Formato";
                    ViewBag.Step2Description = "Selecione o tipo de conversão desejada";
                    ViewBag.Step3Title = "Copie o Resultado";
                    ViewBag.Step3Description = "Copie o texto convertido";
                    ViewBag.InputLabel = "Texto Original";
                    ViewBag.OutputLabel = "Texto Convertido";
                    ViewBag.InputPlaceholder = "Digite ou cole seu texto aqui...";
                    ViewBag.OutputPlaceholder = "O texto convertido aparecerá aqui...";
                    ViewBag.ConvertButtonText = "Converter Texto";
                    ViewBag.ConverterType = "text";
                    ViewBag.OutputType = "text";
                    ViewBag.HasAdvancedOptions = true;
                    break;

                case "csv-json":
                    ViewBag.ConverterTitle = "CONVERSOR CSV PARA JSON";
                    ViewBag.ConverterDescription = "Converta arquivos CSV para formato JSON de forma rápida e fácil";
                    ViewBag.Step1Title = "Upload CSV";
                    ViewBag.Step1Description = "Selecione um arquivo CSV ou cole o conteúdo";
                    ViewBag.Step2Title = "Processar";
                    ViewBag.Step2Description = "Aguarde a conversão automática";
                    ViewBag.Step3Title = "Baixar JSON";
                    ViewBag.Step3Description = "Baixe ou copie o resultado";
                    ViewBag.InputLabel = "Arquivo CSV";
                    ViewBag.OutputLabel = "Resultado JSON";
                    ViewBag.InputPlaceholder = "Cole o conteúdo CSV aqui ou faça upload de um arquivo...";
                    ViewBag.OutputPlaceholder = "O JSON convertido aparecerá aqui...";
                    ViewBag.ConvertButtonText = "Converter para JSON";
                    ViewBag.ConverterType = "text"; // Aceita texto e arquivo
                    ViewBag.OutputType = "text";
                    ViewBag.AcceptedFileTypes = ".csv,.txt";
                    ViewBag.FileHelpText = "Tamanho máximo: 10MB. Formatos: CSV, TXT";
                    break;

                case "image-ocr":
                    ViewBag.ConverterTitle = "CONVERSOR DE IMAGEM PARA TEXTO - OCR ONLINE";
                    ViewBag.ConverterDescription = "Extraia texto de imagens usando tecnologia de Reconhecimento Óptico de Caracteres";
                    ViewBag.Step1Title = "Upload Imagem";
                    ViewBag.Step1Description = "Selecione uma imagem com texto";
                    ViewBag.Step2Title = "Processar OCR";
                    ViewBag.Step2Description = "Aguarde a extração do texto";
                    ViewBag.Step3Title = "Copiar Texto";
                    ViewBag.Step3Description = "Copie ou baixe o texto extraído";
                    ViewBag.InputLabel = "Imagem";
                    ViewBag.OutputLabel = "Texto Extraído";
                    ViewBag.SelectFileText = "SELECIONAR IMAGEM";
                    ViewBag.ConvertButtonText = "Extrair Texto";
                    ViewBag.ConverterType = "file";
                    ViewBag.OutputType = "text";
                    ViewBag.AcceptedFileTypes = ".jpg,.jpeg,.png,.gif,.bmp,.pdf";
                    ViewBag.FileHelpText = "Tamanho máximo: 15MB. Formatos: JPG, PNG, GIF, BMP, PDF";
                    ViewBag.HasAdvancedOptions = true;
                    break;

                default:
                    // Configuração genérica
                    ViewBag.ConverterTitle = converterName.ToUpper();
                    ViewBag.ConverterDescription = "Converta seus arquivos de forma rápida e segura";
                    ViewBag.Step1Title = "Entrada";
                    ViewBag.Step1Description = "Selecione ou cole seu conteúdo";
                    ViewBag.Step2Title = "Processar";
                    ViewBag.Step2Description = "Aguarde o processamento";
                    ViewBag.Step3Title = "Resultado";
                    ViewBag.Step3Description = "Baixe ou copie o resultado";
                    ViewBag.ConvertButtonText = "Converter";
                    ViewBag.ConverterType = "text";
                    ViewBag.OutputType = "text";
                    break;
            }

            // Textos comuns do conversor
            ViewBag.LoadingText = "Processando...";
            ViewBag.ProcessingText = "Convertendo seu arquivo...";
            ViewBag.CopyButtonText = "Copiar";
            ViewBag.ClearButtonText = "Limpar";
            ViewBag.ShareButtonText = "Compartilhar";
            ViewBag.CopiedText = "Copiado!";
            ViewBag.DownloadButtonText = "Baixar";
            ViewBag.DownloadReadyText = "Seu arquivo está pronto!";
            ViewBag.SecurityText = "Seus dados estão seguros conosco";
            ViewBag.DefaultErrorMessage = "Erro ao processar. Tente novamente.";
            ViewBag.AdvancedOptionsText = "Opções Avançadas";
            ViewBag.PreviewPlaceholder = "O resultado aparecerá aqui...";

            // Configurações de benefícios
            ViewBag.BenefitsTitle = "Por Que Usar Nossa Ferramenta?";
            ViewBag.BenefitsSubtitle = "Descubra os benefícios de nossa solução";
            ViewBag.FinalCtaTitle = "Pronto para Converter?";
            ViewBag.FinalCtaSubtitle = "Use nossa ferramenta gratuita agora mesmo";
            ViewBag.FinalCtaButtonText = "Começar Conversão";

            // Features padrão se não especificadas
            if (ViewBag.Feature1Title == null)
            {
                ViewBag.Feature1Title = "Rápido e Fácil";
                ViewBag.Feature1Description = "Conversão instantânea sem complicações";
                ViewBag.Feature2Title = "Seguro";
                ViewBag.Feature2Description = "Seus dados são processados com segurança";
                ViewBag.Feature3Title = "Gratuito";
                ViewBag.Feature3Description = "Use nossa ferramenta sem custos";
            }
        }

        protected virtual void SetupEnglishConverterContent(string converterType, string converterName)
        {
            switch (converterType)
            {
                case "text-case":
                    ViewBag.ConverterTitle = "TEXT CASE CONVERTER";
                    ViewBag.ConverterDescription = "Convert text between uppercase, lowercase, title case and sentence case";
                    ViewBag.Step1Title = "Paste Text";
                    ViewBag.Step1Description = "Type or paste the text you want to convert";
                    ViewBag.Step2Title = "Choose Format";
                    ViewBag.Step2Description = "Select the desired conversion type";
                    ViewBag.Step3Title = "Copy Result";
                    ViewBag.Step3Description = "Copy the converted text";
                    ViewBag.InputLabel = "Original Text";
                    ViewBag.OutputLabel = "Converted Text";
                    ViewBag.InputPlaceholder = "Type or paste your text here...";
                    ViewBag.OutputPlaceholder = "Converted text will appear here...";
                    ViewBag.ConvertButtonText = "Convert Text";
                    break;

                case "csv-json":
                    ViewBag.ConverterTitle = "CSV TO JSON CONVERTER";
                    ViewBag.ConverterDescription = "Convert CSV files to JSON format quickly and easily";
                    ViewBag.Step1Title = "Upload CSV";
                    ViewBag.Step1Description = "Select a CSV file or paste content";
                    ViewBag.Step2Title = "Process";
                    ViewBag.Step2Description = "Wait for automatic conversion";
                    ViewBag.Step3Title = "Download JSON";
                    ViewBag.Step3Description = "Download or copy the result";
                    ViewBag.ConvertButtonText = "Convert to JSON";
                    break;

                case "image-ocr":
                    ViewBag.ConverterTitle = "IMAGE TO TEXT CONVERTER - OCR ONLINE";
                    ViewBag.ConverterDescription = "Extract text from images using Optical Character Recognition technology";
                    ViewBag.Step1Title = "Upload Image";
                    ViewBag.Step1Description = "Select an image with text";
                    ViewBag.Step2Title = "Process OCR";
                    ViewBag.Step2Description = "Wait for text extraction";
                    ViewBag.Step3Title = "Copy Text";
                    ViewBag.Step3Description = "Copy or download extracted text";
                    ViewBag.SelectFileText = "SELECT IMAGE";
                    ViewBag.ConvertButtonText = "Extract Text";
                    break;

                default:
                    ViewBag.ConverterTitle = converterName.ToUpper();
                    ViewBag.ConverterDescription = "Convert your files quickly and securely";
                    ViewBag.ConvertButtonText = "Convert";
                    break;
            }

            // Common English texts
            ViewBag.LoadingText = "Processing...";
            ViewBag.ProcessingText = "Converting your file...";
            ViewBag.CopyButtonText = "Copy";
            ViewBag.ClearButtonText = "Clear";
            ViewBag.ShareButtonText = "Share";
            ViewBag.CopiedText = "Copied!";
            ViewBag.DownloadButtonText = "Download";
            ViewBag.SecurityText = "Your data is safe with us";
            ViewBag.BenefitsTitle = "Why Use Our Tool?";
            ViewBag.FinalCtaTitle = "Ready to Convert?";
        }

        protected virtual void SetupSpanishConverterContent(string converterType, string converterName)
        {
            switch (converterType)
            {
                case "text-case":
                    ViewBag.ConverterTitle = "CONVERTIDOR DE MAYÚSCULAS Y MINÚSCULAS";
                    ViewBag.ConverterDescription = "Convierte texto entre mayúsculas, minúsculas, título y oración";
                    ViewBag.ConvertButtonText = "Convertir Texto";
                    break;

                case "csv-json":
                    ViewBag.ConverterTitle = "CONVERTIDOR CSV A JSON";
                    ViewBag.ConverterDescription = "Convierte archivos CSV a formato JSON de forma rápida y fácil";
                    ViewBag.ConvertButtonText = "Convertir a JSON";
                    break;

                case "image-ocr":
                    ViewBag.ConverterTitle = "CONVERTIDOR DE IMAGEN A TEXTO - OCR EN LÍNEA";
                    ViewBag.ConverterDescription = "Extrae texto de imágenes usando tecnología de Reconocimiento Óptico de Caracteres";
                    ViewBag.SelectFileText = "SELECCIONAR IMAGEN";
                    ViewBag.ConvertButtonText = "Extraer Texto";
                    break;

                default:
                    ViewBag.ConverterTitle = converterName.ToUpper();
                    ViewBag.ConverterDescription = "Convierte tus archivos de forma rápida y segura";
                    ViewBag.ConvertButtonText = "Convertir";
                    break;
            }

            // Common Spanish texts
            ViewBag.LoadingText = "Procesando...";
            ViewBag.ProcessingText = "Convirtiendo tu archivo...";
            ViewBag.CopyButtonText = "Copiar";
            ViewBag.ClearButtonText = "Limpiar";
            ViewBag.CopiedText = "¡Copiado!";
            ViewBag.SecurityText = "Tus datos están seguros con nosotros";
            ViewBag.BenefitsTitle = "¿Por Qué Usar Nuestra Herramienta?";
            ViewBag.FinalCtaTitle = "¿Listo para Convertir?";
        }

        // Resto dos métodos permanece igual...
        protected void SetupPortugueseContent()
        {
            // Menu
            ViewBag.MenuHome = "Início";
            ViewBag.MenuAbout = "Sobre";
            ViewBag.MenuContact = "Contato";
            ViewBag.MenuPrivacy = "Privacidade";
            ViewBag.MenuTerms = "Termos";

            // Footer
            ViewBag.FooterDescription = "Transformando dados 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";

            // Contact info
            ViewBag.ContactEmail = "contato@seusite.com";
            ViewBag.ContactPhone = "(11) 99999-9999";
            ViewBag.ContactAddress = "São Paulo, SP";
        }

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

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

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

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

            // Footer
            ViewBag.FooterDescription = "Transformando datos 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";

            // Contact info
            ViewBag.ContactEmail = "contacto@tusitioweb.com";
            ViewBag.ContactPhone = "+34 123 456 789";
            ViewBag.ContactAddress = "Madrid, España";
        }

        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;
            }
        }
    }
}