from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.views.generic import TemplateView,View

from .models import Subscriber
from django.views.generic import TemplateView
from django.utils import timezone
from django.contrib import messages
from at_django_boilerplate.backend_admin.models import SEOConfiguration

# at_django_boilerplate/core/views.py
from django.shortcuts import redirect
from django.views.generic import TemplateView
import random
from django.shortcuts import redirect
from django.views.generic import TemplateView
from django.utils import timezone
from .models import ABTestRecord
from django.urls import reverse_lazy
from at_django_boilerplate.accounts.models import CustomUser
from django.contrib.auth import login
from at_django_boilerplate.utils.encryption_utils import EncryptionUtils
enc = EncryptionUtils()

class IndexView(TemplateView):
    template_name = 'index.html'  # default (we'll override dynamically)

    def dispatch(self, request, *args, **kwargs):
        # Redirect logged-in users
        if request.user.is_authenticated:
            return redirect('dashboard')

        # Assign variant (if not already assigned)
        variant = request.session.get('ab_variant')
        if not variant:
            variant = random.choice(['A', 'B'])
            request.session['ab_variant'] = variant

            # Ensure session exists
            if not request.session.session_key:
                request.session.create()

            # Optional: record in DB for analytics
            ABTestRecord.objects.get_or_create(
                session_key=request.session.session_key,
                defaults={'variant': variant},
            )

        # Store chosen template name
        self.template_name = 'index.html'
        return super().dispatch(request, *args, **kwargs)


    
class DashboardView(TemplateView):
    template_name = 'dashboard.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['meta_title'] = "Dashboard - Register Your Startup"
        context['meta_description'] = "Manage your startup journey with Register Your Startup."
        return context
    
def get_seo():
    return SEOConfiguration.objects.first()

class TermsView(TemplateView):
    template_name = 'legal/toc.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        seo = SEOConfiguration.objects.first()

        context["meta_title"] = seo.term_and_con_meta_title if seo else "Terms & Conditions - Zestato"
        context["meta_description"] = seo.term_and_con_meta_description if seo else "View our latest terms and conditions."
        return context
    

class PrivacyPolicyView(TemplateView):
    template_name = 'legal/privacy.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        seo = SEOConfiguration.objects.first()

        context["meta_title"] = seo.privacy_pol_meta_title if seo else "Privacy Policy - Zestato"
        context["meta_description"] = seo.privacy_pol_meta_description if seo else "Read Zestato's privacy practices and data usage policy."
        return context



class DataProtectionView(TemplateView):
    template_name = 'legal/data_protection.html'

class ImprintView(TemplateView):
    template_name = 'legal/imprint.html'

class PressView(TemplateView):
    template_name = 'company/press.html'

class SuccessStories(TemplateView):
    template_name = 'company/success_stories.html'

class Training(TemplateView):
    template_name = 'company/training.html'

class HelpAndSupport(TemplateView):
    template_name = 'company/help_and_support.html'
    
class AboutUsView(TemplateView):
    template_name = 'company/about_us.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        seo = SEOConfiguration.objects.first()

        context["meta_title"] = seo.about_meta_title if seo else "About Us - Zestato"
        context["meta_description"] = seo.about_meta_description if seo else "Learn about Zestato's mission, values, and team."
        return context

class BlogsView(TemplateView):
    template_name = 'company/blog.html'

class OurCoreTeam(TemplateView):
    template_name = 'company/ourcoreteam.html'

class CookiePolicy(TemplateView):
    template_name = 'legal/cookiepolicy.html'



class CareersView(TemplateView):
    template_name = 'company/careers.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        seo = SEOConfiguration.objects.first()
        context["meta_title"] = seo.career_meta_title if seo else "Careers - Zestato"
        context["meta_description"] = seo.career_meta_description if seo else "Explore exciting career opportunities at Zestato."
        return context

class FaqView(TemplateView):
    template_name = 'company/faq.html'


def robots_txt(request):
    seo = SEOConfiguration.objects.first()

    lines = [
        "User-Agent: *",
        "Disallow: /admin/",
        "Allow: /",
    ]

    # Optionally add canonical URLs as Sitemap entries (if available)
    if seo:
        if seo.term_and_con_canonical_url:
            lines.append(f"Sitemap: {seo.term_and_con_canonical_url}")
        if seo.privacy_pol_canonical_url:
            lines.append(f"Sitemap: {seo.privacy_pol_canonical_url}")

    return HttpResponse("\n".join(lines), content_type="text/plain")



def custom_500(request):
    # You can add extra context or logging here
    return render(request, 'defaults/500.html', status=500)

def custom_404(request, exception=None):
    # You can add any additional context here if necessary
    return render(request, 'defaults/404.html', status=404)


def custom_400(request, exception=None):
    # You can customize the context further if needed
    return render(request, 'defaults/400.html', status=400)

def custom_403(request, exception=None):
    # You can customize the context further if needed
    return render(request, 'defaults/403.html', status=403)


def subscribe_view(request):
    if request.method == "POST":
        email = request.POST.get("email")
        if email:
            # created = False
            # subscriber = None
            subscriber, created = Subscriber.objects.get_or_create(email=email)

            if created:
                messages.success(request, "Thank you for subscribing!")
            else:
                if subscriber.is_active:
                    messages.warning(request, "You are already subscribed.")
                else:
                    subscriber.is_active = True
                    subscriber.subscribed_at = timezone.now()  # update date
                    subscriber.save()
                    messages.success(request, "Welcome back! You have been re-subscribed.")
        return redirect("index")

    return render(request, "company/subscriber.html")



def unsubscribe_view(request, id):
    try:
        subscriber = Subscriber.objects.get(id=id)
        if subscriber.is_active:
            subscriber.is_active = False
            subscriber.save()
            messages.success(request, "You have been unsubscribed successfully.")
        else:
            messages.info(request, "You are already unsubscribed.")
    except Subscriber.DoesNotExist:
        messages.error(request, "Invalid unsubscribe link.")

    return redirect("index")

