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


namespace OnlyOneAccessTemplate.Controllers
{

    public class HomeController : BaseController
    {
        public HomeController(
            ISiteConfigurationService siteConfig,
            ILanguageService languageService,
            ISeoService seoService,
            IMemoryCache cache,
            IConfiguration configuration)
            : base(siteConfig, languageService, seoService, cache, configuration)
        {
        }

        public async Task<IActionResult> Index()
        {
            var language = GetCurrentLanguage();

            // Get page content from database
            var pageContent = await _siteConfig.GetPageContentAsync(language, "index");

            // If no content exists, create default content
            if (pageContent == null)
            {
                await CreateDefaultContentAsync(language);
                pageContent = await _siteConfig.GetPageContentAsync(language, "index");
            }

            // Set current page for navigation
            ViewBag.CurrentPage = "home";

            return View(pageContent);
        }

        public async Task<IActionResult> About()
        {
            var language = GetCurrentLanguage();
            var pageContent = await _siteConfig.GetPageContentAsync(language, "about");

            if (pageContent == null)
            {
                await CreateDefaultContentAsync(language);
                pageContent = await _siteConfig.GetPageContentAsync(language, "about");
            }

            ViewBag.CurrentPage = "about";
            return View(pageContent);
        }

        public async Task<IActionResult> Contact()
        {
            var language = GetCurrentLanguage();
            var pageContent = await _siteConfig.GetPageContentAsync(language, "contact");

            ViewBag.CurrentPage = "contact";
            return View(pageContent);
        }

        [HttpGet("setup-data")]
        public async Task<IActionResult> SetupDefaultData()
        {
            try
            {
                var languages = new[] { "pt", "en", "es" };

                foreach (var language in languages)
                {
                    await CreateDefaultContentAsync(language);
                }

                return Json(new { success = true, message = "Dados padrão criados com sucesso!" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }

        [HttpGet("privacy")]
        public IActionResult Privacy()
        {
            ViewBag.CurrentPage = "privacy";
            SetPageSeo(
                "Política de Privacidade",
                "Nossa política de privacidade e proteção de dados",
                "privacidade, proteção de dados, lgpd"
            );
            return View();
        }

        [HttpGet("terms")]
        public IActionResult Terms()
        {
            ViewBag.CurrentPage = "terms";
            SetPageSeo(
                "Termos de Uso",
                "Termos e condições de uso do nosso serviço",
                "termos, condições, uso"
            );
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View();
        }

        private async Task CreateDefaultContentAsync(string language)
        {
            try
            {
                // Check if configuration already exists
                var configExists = await _siteConfig.ConfigurationExistsAsync(language);
                if (configExists) return;

                // Create default configuration with sample content
                var siteConfig = new SiteConfiguration
                {
                    Language = language,
                    Seo = CreateDefaultSeoConfig(language),
                    Pages = CreateDefaultPages(language),
                    Conversion = CreateDefaultConversionConfig(language),
                    CreatedAt = DateTime.UtcNow,
                    UpdatedAt = DateTime.UtcNow
                };

                await _siteConfig.UpdateConfigurationAsync(siteConfig);
            }
            catch (Exception ex)
            {
                // Log error but don't break the page
                Console.WriteLine($"Error creating default content: {ex.Message}");
            }
        }

        private SeoConfig CreateDefaultSeoConfig(string language)
        {
            return language switch
            {
                "en" => new SeoConfig
                {
                    SiteName = "OnlyOne Access Template",
                    DefaultTitle = "Transform Your Business - Conversion Template",
                    DefaultDescription = "Professional conversion solutions to boost your business results with proven methodology",
                    DefaultKeywords = "conversion, business, marketing, results, template",
                    TwitterCard = "summary_large_image",
                    GoogleTagManagerId = "GTM-XXXXXXX",
                    GoogleAnalyticsId = "GA-XXXXXXXX",
                    Author = "OnlyOne Access Team",
                    OgImage = "/img/og-image-en.jpg"
                },
                "es" => new SeoConfig
                {
                    SiteName = "OnlyOne Access Template",
                    DefaultTitle = "Transforma Tu Negocio - Template de Conversión",
                    DefaultDescription = "Soluciones profesionales de conversión para potenciar los resultados de tu negocio",
                    DefaultKeywords = "conversión, negocio, marketing, resultados, plantilla",
                    TwitterCard = "summary_large_image",
                    GoogleTagManagerId = "GTM-XXXXXXX",
                    GoogleAnalyticsId = "GA-XXXXXXXX",
                    Author = "Equipo OnlyOne Access",
                    OgImage = "/img/og-image-es.jpg"
                },
                _ => new SeoConfig
                {
                    SiteName = "OnlyOne Access Template",
                    DefaultTitle = "Transforme Seu Negócio - Template de Conversão",
                    DefaultDescription = "Soluções profissionais de conversão para alavancar os resultados do seu negócio",
                    DefaultKeywords = "conversão, negócio, marketing, resultados, template",
                    TwitterCard = "summary_large_image",
                    GoogleTagManagerId = "GTM-XXXXXXX",
                    GoogleAnalyticsId = "GA-XXXXXXXX",
                    Author = "Equipe OnlyOne Access",
                    OgImage = "/img/og-image-pt.jpg"
                }
            };
        }

        private Dictionary<string, PageContent> CreateDefaultPages(string language)
        {
            return language switch
            {
                "en" => new Dictionary<string, PageContent>
                {
                    ["index"] = new PageContent
                    {
                        Title = "Transform Your Business Today",
                        Description = "Increase your sales by up to 300% with our proven methodology and expert support",
                        Keywords = "business transformation, conversion, sales growth, methodology",
                        H1 = "Transform Your Business Today",
                        MetaTitle = "Business Transformation | Conversion Solutions",
                        Blocks = CreateEnglishBlocks(),
                        IsActive = true,
                        PublishDate = DateTime.UtcNow
                    },
                    ["about"] = new PageContent
                    {
                        Title = "About Us - Our Mission",
                        Description = "Learn about our mission to help businesses achieve better conversion rates",
                        H1 = "About Our Company",
                        MetaTitle = "About Us | Conversion Experts"
                    }
                },
                "es" => new Dictionary<string, PageContent>
                {
                    ["index"] = new PageContent
                    {
                        Title = "Transforma Tu Negocio Hoy",
                        Description = "Aumenta tus ventas hasta un 300% con nuestra metodología probada y soporte especializado",
                        Keywords = "transformación empresarial, conversión, crecimiento de ventas, metodología",
                        H1 = "Transforma Tu Negocio Hoy",
                        MetaTitle = "Transformación Empresarial | Soluciones de Conversión",
                        Blocks = CreateSpanishBlocks(),
                        IsActive = true,
                        PublishDate = DateTime.UtcNow
                    },
                    ["about"] = new PageContent
                    {
                        Title = "Acerca de Nosotros - Nuestra Misión",
                        Description = "Conoce nuestra misión de ayudar a las empresas a lograr mejores tasas de conversión",
                        H1 = "Acerca de Nuestra Empresa",
                        MetaTitle = "Acerca de Nosotros | Expertos en Conversión"
                    }
                },
                _ => new Dictionary<string, PageContent>
                {
                    ["index"] = new PageContent
                    {
                        Title = "Transforme Seu Negócio Hoje",
                        Description = "Aumente suas vendas em até 300% com nossa metodologia comprovada e suporte especializado",
                        Keywords = "transformação empresarial, conversão, crescimento de vendas, metodologia",
                        H1 = "Transforme Seu Negócio Hoje",
                        MetaTitle = "Transformação Empresarial | Soluções de Conversão",
                        Blocks = CreatePortugueseBlocks(),
                        IsActive = true,
                        PublishDate = DateTime.UtcNow
                    },
                    ["about"] = new PageContent
                    {
                        Title = "Sobre Nós - Nossa Missão",
                        Description = "Conheça nossa missão de ajudar empresas a alcançar melhores taxas de conversão",
                        H1 = "Sobre Nossa Empresa",
                        MetaTitle = "Sobre Nós | Especialistas em Conversão"
                    }
                }
            };
        }

        private List<ContentBlock> CreatePortugueseBlocks()
        {
            return new List<ContentBlock>
        {
            new ContentBlock
            {
                Type = "hero",
                Title = "Transforme Seu Negócio com Nossa <span class='text-gradient'>Solução Inovadora</span>",
                Content = "Aumente suas vendas em até 300% com nossa metodologia comprovada, suporte especializado e resultados garantidos em 30 dias.",
                ImageUrl = "/img/hero-pt.jpg",
                ButtonText = "Começar Transformação",
                ButtonUrl = "#conversion-form",
                Order = 1,
                Properties = new Dictionary<string, object>
                {
                    { "badge", "🚀 Mais de 1000 empresas transformadas" },
                    { "features", new[] { "✅ Metodologia comprovada", "✅ Suporte 24/7", "✅ Resultados em 30 dias" } },
                    { "social_proof", "Mais de 500 avaliações 5 estrelas" }
                }
            },
            new ContentBlock
            {
                Type = "features",
                Title = "Por Que Escolher Nossa Solução?",
                Content = "Descubra os benefícios que já transformaram mais de 1000 empresas em todo o Brasil",
                Order = 2,
                Properties = new Dictionary<string, object>
                {
                    { "feature_list", new[]
                        {
                            new Dictionary<string, object>
                            {
                                { "icon", "fas fa-rocket" },
                                { "title", "Resultados Rápidos" },
                                { "description", "Veja os primeiros resultados em até 30 dias com nossa metodologia testada" }
                            },
                            new Dictionary<string, object>
                            {
                                { "icon", "fas fa-shield-alt" },
                                { "title", "Garantia Total" },
                                { "description", "100% de garantia ou seu dinheiro de volta. Assumimos o risco por você" }
                            },
                            new Dictionary<string, object>
                            {
                                { "icon", "fas fa-users" },
                                { "title", "Suporte Especializado" },
                                { "description", "Equipe dedicada 24/7 para garantir seu sucesso em cada etapa" }
                            },
                            new Dictionary<string, object>
                            {
                                { "icon", "fas fa-chart-line" },
                                { "title", "Crescimento Sustentável" },
                                { "description", "Estratégias de longo prazo para crescimento consistente e duradouro" }
                            },
                            new Dictionary<string, object>
                            {
                                { "icon", "fas fa-cog" },
                                { "title", "Automatização" },
                                { "description", "Processos automatizados que trabalham para você 24 horas por dia" }
                            },
                            new Dictionary<string, object>
                            {
                                { "icon", "fas fa-trophy" },
                                { "title", "Casos de Sucesso" },
                                { "description", "Mais de 1000 empresas já alcançaram resultados extraordinários" }
                            }
                        }
                    }
                }
            },
            new ContentBlock
            {
                Type = "testimonials",
                Title = "O Que Nossos Clientes Dizem",
                Content = "Mais de 1000 empresas já transformaram seus resultados. Veja alguns depoimentos:",
                Order = 3,
                Properties = new Dictionary<string, object>
                {
                    { "testimonials", new[]
                        {
                            new Dictionary<string, object>
                            {
                                { "quote", "Aumentamos nossas vendas em 250% em apenas 3 meses. A metodologia realmente funciona e o suporte é excepcional!" },
                                { "name", "Maria Silva" },
                                { "position", "CEO, TechStart Brasil" },
                                { "avatar", "/img/testimonial-1.jpg" }
                            },
                            new Dictionary<string, object>
                            {
                                { "quote", "O ROI foi incrível. Recuperamos o investimento em 30 dias e continuamos crescendo desde então." },
                                { "name", "João Santos" },
                                { "position", "Diretor Comercial, InovaCorp" },
                                { "avatar", "/img/testimonial-2.jpg" }
                            },
                            new Dictionary<string, object>
                            {
                                { "quote", "Finalmente encontramos uma solução que entrega o que promete. Resultados desde o primeiro mês!" },
                                { "name", "Ana Costa" },
                                { "position", "Fundadora, GrowBiz" },
                                { "avatar", "/img/testimonial-3.jpg" }
                            }
                        }
                    }
                }
            },
            new ContentBlock
            {
                Type = "cta",
                Title = "Pronto para <span class='text-warning'>Transformar</span> Seu Negócio?",
                Content = "Junte-se a mais de 1000 empresas que já alcançaram resultados extraordinários com nossa metodologia comprovada.",
                ButtonText = "Começar Minha Transformação",
                ButtonUrl = "#conversion-form",
                Order = 4,
                Properties = new Dictionary<string, object>
                {
                    { "urgency_badge", "⚡ Últimas vagas da semana" },
                    { "guarantee", "🛡️ Garantia de 30 dias ou seu dinheiro de volta" },
                    { "secondary_button_text", "Assistir Demonstração" },
                    { "secondary_button_url", "#demo-video" }
                }
            }
        };
        }

        private List<ContentBlock> CreateEnglishBlocks()
        {
            return new List<ContentBlock>
        {
            new ContentBlock
            {
                Type = "hero",
                Title = "Transform Your Business with Our <span class='text-gradient'>Innovative Solution</span>",
                Content = "Increase your sales by up to 300% with our proven methodology, expert support and guaranteed results in 30 days.",
                ImageUrl = "/img/hero-en.jpg",
                ButtonText = "Start Transformation",
                ButtonUrl = "#conversion-form",
                Order = 1,
                Properties = new Dictionary<string, object>
                {
                    { "badge", "🚀 Over 1000 companies transformed" },
                    { "features", new[] { "✅ Proven methodology", "✅ 24/7 Support", "✅ Results in 30 days" } },
                    { "social_proof", "Over 500 five-star reviews" }
                }
            },
            new ContentBlock
            {
                Type = "features",
                Title = "Why Choose Our Solution?",
                Content = "Discover the benefits that have already transformed over 1000 companies worldwide",
                Order = 2,
                Properties = new Dictionary<string, object>
                {
                    { "feature_list", new[]
                        {
                            new Dictionary<string, object>
                            {
                                { "icon", "fas fa-rocket" },
                                { "title", "Fast Results" },
                                { "description", "See first results within 30 days with our tested methodology" }
                            },
                            new Dictionary<string, object>
                            {
                                { "icon", "fas fa-shield-alt" },
                                { "title", "Full Guarantee" },
                                { "description", "100% guarantee or your money back. We take the risk for you" }
                            },
                            new Dictionary<string, object>
                            {
                                { "icon", "fas fa-users" },
                                { "title", "Expert Support" },
                                { "description", "24/7 dedicated team to ensure your success at every step" }
                            }
                        }
                    }
                }
            },
            new ContentBlock
            {
                Type = "testimonials",
                Title = "What Our Clients Say",
                Content = "Over 1000 companies have already transformed their results. See some testimonials:",
                Order = 3,
                Properties = new Dictionary<string, object>
                {
                    { "testimonials", new[]
                        {
                            new Dictionary<string, object>
                            {
                                { "quote", "We increased our sales by 250% in just 3 months. The methodology really works!" },
                                { "name", "Mary Johnson" },
                                { "position", "CEO, TechStart USA" },
                                { "avatar", "/img/testimonial-en-1.jpg" }
                            }
                        }
                    }
                }
            },
            new ContentBlock
            {
                Type = "cta",
                Title = "Ready to <span class='text-warning'>Transform</span> Your Business?",
                Content = "Join over 1000 companies that have already achieved extraordinary results.",
                ButtonText = "Start My Transformation",
                ButtonUrl = "#conversion-form",
                Order = 4
            }
        };
        }

        private List<ContentBlock> CreateSpanishBlocks()
        {
            return new List<ContentBlock>
        {
            new ContentBlock
            {
                Type = "hero",
                Title = "Transforma Tu Negocio con Nuestra <span class='text-gradient'>Solución Innovadora</span>",
                Content = "Aumenta tus ventas hasta un 300% con nuestra metodología probada, soporte especializado y resultados garantizados en 30 días.",
                ImageUrl = "/img/hero-es.jpg",
                ButtonText = "Comenzar Transformación",
                ButtonUrl = "#conversion-form",
                Order = 1,
                Properties = new Dictionary<string, object>
                {
                    { "badge", "🚀 Más de 1000 empresas transformadas" },
                    { "features", new[] { "✅ Metodología probada", "✅ Soporte 24/7", "✅ Resultados en 30 días" } },
                    { "social_proof", "Más de 500 reseñas de 5 estrellas" }
                }
            },
            new ContentBlock
            {
                Type = "features",
                Title = "¿Por Qué Elegir Nuestra Solución?",
                Content = "Descubre los beneficios que ya han transformado más de 1000 empresas en todo el mundo",
                Order = 2
            },
            new ContentBlock
            {
                Type = "testimonials",
                Title = "Lo Que Dicen Nuestros Clientes",
                Content = "Más de 1000 empresas ya han transformado sus resultados. Ve algunos testimonios:",
                Order = 3
            },
            new ContentBlock
            {
                Type = "cta",
                Title = "¿Listo para <span class='text-warning'>Transformar</span> Tu Negocio?",
                Content = "Únete a más de 1000 empresas que ya han logrado resultados extraordinarios.",
                ButtonText = "Comenzar Mi Transformación",
                ButtonUrl = "#conversion-form",
                Order = 4
            }
        };
        }

        private ConversionConfig CreateDefaultConversionConfig(string language)
        {
            return new ConversionConfig
            {
                FormAction = "/conversion/submit",
                ThankYouPage = language switch
                {
                    "en" => "/en/thank-you",
                    "es" => "/es/gracias",
                    _ => "/obrigado"
                },
                FormFields = language switch
                {
                    "en" => new List<FormField>
                {
                    new() { Name = "name", Type = "text", Label = "Full Name", Placeholder = "Enter your full name", Required = true, Order = 1 },
                    new() { Name = "email", Type = "email", Label = "Email Address", Placeholder = "Enter your email", Required = true, Order = 2 },
                    new() { Name = "phone", Type = "tel", Label = "Phone Number", Placeholder = "Enter your phone number", Required = false, Order = 3 },
                    new() { Name = "company", Type = "text", Label = "Company Name", Placeholder = "Enter your company name", Required = false, Order = 4 }
                },
                    "es" => new List<FormField>
                {
                    new() { Name = "name", Type = "text", Label = "Nombre Completo", Placeholder = "Ingresa tu nombre completo", Required = true, Order = 1 },
                    new() { Name = "email", Type = "email", Label = "Correo Electrónico", Placeholder = "Ingresa tu correo", Required = true, Order = 2 },
                    new() { Name = "phone", Type = "tel", Label = "Número de Teléfono", Placeholder = "Ingresa tu teléfono", Required = false, Order = 3 },
                    new() { Name = "company", Type = "text", Label = "Nombre de la Empresa", Placeholder = "Ingresa el nombre de tu empresa", Required = false, Order = 4 }
                },
                    _ => new List<FormField>
                {
                    new() { Name = "name", Type = "text", Label = "Nome Completo", Placeholder = "Digite seu nome completo", Required = true, Order = 1 },
                    new() { Name = "email", Type = "email", Label = "E-mail", Placeholder = "Digite seu e-mail", Required = true, Order = 2 },
                    new() { Name = "phone", Type = "tel", Label = "Telefone", Placeholder = "Digite seu telefone", Required = false, Order = 3 },
                    new() { Name = "company", Type = "text", Label = "Nome da Empresa", Placeholder = "Digite o nome da sua empresa", Required = false, Order = 4 }
                }
                }
            };
        }
    }
}