from django.contrib import messages
from django.db.models import Count
from django.http import HttpResponse, JsonResponse
from django.shortcuts import redirect, render
from django.urls import reverse
from django.views.generic import TemplateView

from blog.models import BlogPost
from companies.utils import apply_open_jobs_count
from jobs.models import Job, JobCategory, SavedJob
from jobs.querysets import with_job_logo
from jobs.status import open_jobs_q
from podcast.models import PodcastEpisode
from seekers.models import SeekerProfile
from subscriptions.carousel import carousel_companies_queryset, carousel_seekers_queryset
from testimonials.models import Testimonial

from .forms import ContactForm, PartnerInquiryForm
from .partner_content import (
    BUILD_TOGETHER,
    DEPT_SUBJECT_MAP,
    ECOSYSTEM,
    FINAL_CTA,
    HOW_IT_WORKS,
    OPEN_IDEA,
    PARTNER_CONTACT,
    PARTNER_HERO,
    PARTNERSHIP_MODELS,
    SOCIAL_LINKS,
    VALUE_SECTION,
    WHO_CAN_PARTNER,
    WHY_PARTNER,
)
from .locations import ZAMBIA_TOWNS
from .models import ContactMessage
from .notifications import notify_admin_contact_message
from .stats import get_platform_stats


class IndexView(TemplateView):
    template_name = 'home/index.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        context['latest_jobs'] = with_job_logo(
            Job.objects.filter(open_jobs_q()).select_related('category')
        )[:8]
        saved_ids = set()
        user = self.request.user
        if user.is_authenticated:
            job_ids = [job.pk for job in context['latest_jobs']]
            saved_ids = set(
                SavedJob.objects.filter(user=user, job_id__in=job_ids).values_list('job_id', flat=True)
            )
        context['saved_ids'] = saved_ids

        context['stats'] = get_platform_stats()

        # All official categories: those with open jobs first, then the rest in official number order.
        context['job_categories'] = list(
            JobCategory.active()
            .annotate(job_count=Count('jobs', filter=open_jobs_q('jobs')))
            .order_by('-job_count', 'number', 'name')
        )

        context['featured_companies'] = apply_open_jobs_count(
            list(carousel_companies_queryset()[:10])
        )
        context['featured_seekers'] = list(carousel_seekers_queryset()[:8])
        from seekers.profile_access import viewer_sees_full_seeker_listings
        context['show_full_seeker_details'] = viewer_sees_full_seeker_listings(self.request)

        featured_blog = BlogPost.objects.filter(is_published=True, is_featured=True).first()
        context['featured_blog'] = featured_blog
        latest_posts = BlogPost.objects.filter(is_published=True)
        if featured_blog:
            latest_posts = latest_posts.exclude(pk=featured_blog.pk)
        context['latest_blog_posts'] = latest_posts[:4]

        context['featured_testimonial'] = Testimonial.objects.filter(
            is_approved=True, is_featured=True
        ).first()
        context['home_testimonials'] = Testimonial.objects.filter(is_approved=True)[:3]

        featured_podcast = PodcastEpisode.objects.filter(is_published=True, is_featured=True).first()
        context['featured_podcast'] = featured_podcast
        latest_episodes = PodcastEpisode.objects.filter(is_published=True)
        if featured_podcast:
            latest_episodes = latest_episodes.exclude(pk=featured_podcast.pk)
        context['latest_podcast_episodes'] = latest_episodes[:4]
        context['search_locations'] = ZAMBIA_TOWNS

        return context


class AboutView(TemplateView):
    template_name = 'home/about.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['stats'] = get_platform_stats()
        return context


class PrivacyPolicyView(TemplateView):
    template_name = 'home/privacy.html'


class TermsOfServiceView(TemplateView):
    template_name = 'home/terms.html'


class FaqView(TemplateView):
    template_name = 'home/faq.html'

    def get_context_data(self, **kwargs):
        from .faq_content import filter_faq_sections

        context = super().get_context_data(**kwargs)
        query = self.request.GET.get('q', '').strip()
        sections = filter_faq_sections(query)
        total_items = sum(len(section['items']) for section in sections)
        context.update({
            'query': query,
            'faq_sections': sections,
            'faq_total': total_items,
            'faq_page_title': 'FAQ for Professionals – PEZAJOB',
            'faq_subheading': 'FAQs for Professionals',
            'faq_breadcrumb': 'FAQ',
            'faq_url_name': 'home:faq',
            'faq_contact_cta': 'Contact PezaJob',
            'faq_show_help_block': True,
        })
        return context


class CompanyFaqView(TemplateView):
    template_name = 'home/faq.html'

    def get_context_data(self, **kwargs):
        from .company_faq_content import filter_company_faq_sections

        context = super().get_context_data(**kwargs)
        query = self.request.GET.get('q', '').strip()
        sections = filter_company_faq_sections(query)
        total_items = sum(len(section['items']) for section in sections)
        context.update({
            'query': query,
            'faq_sections': sections,
            'faq_total': total_items,
            'faq_page_title': 'FAQ for Companies – PEZAJOB',
            'faq_subheading': 'FAQs for Companies',
            'faq_breadcrumb': 'Company FAQ',
            'faq_url_name': 'home:company_faq',
            'faq_contact_cta': 'Contact Peza Job Zambia',
            'faq_show_help_block': True,
        })
        return context


class ServicesView(TemplateView):
    template_name = 'home/services.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        tab = self.request.GET.get('tab', 'corporate')
        if tab not in ('corporate', 'individual'):
            tab = 'corporate'
        context['active_tab'] = tab
        return context


def contact_view(request):
    form = ContactForm(request.POST or None)
    if request.method == 'POST' and form.is_valid():
        message = ContactMessage.objects.create(**form.cleaned_data)
        notify_admin_contact_message(message)
        messages.success(
            request,
            'Thank you! Your message has been sent. We will respond within 24 hours.',
        )
        return redirect(reverse('home:contact'))
    return render(request, 'home/contact.html', {'form': form})


def partner_view(request):
    initial = {}
    dept = request.GET.get('dept', '').strip().lower()
    if dept in DEPT_SUBJECT_MAP:
        initial['subject'] = DEPT_SUBJECT_MAP[dept]

    form = PartnerInquiryForm(request.POST or None, initial=initial if request.method == 'GET' else None)
    if request.method == 'POST' and form.is_valid():
        message = form.save()
        notify_admin_contact_message(message)
        messages.success(
            request,
            'Thank you for your interest in partnering with PezaJob. Our team will review your enquiry and get in touch with you.',
        )
        return redirect(reverse('home:partner') + '#contact-form')

    return render(
        request,
        'home/partner.html',
        {
            'form': form,
            'partner_contact': PARTNER_CONTACT,
            'partner_hero': PARTNER_HERO,
            'value_section': VALUE_SECTION,
            'who_can_partner': WHO_CAN_PARTNER,
            'build_together': BUILD_TOGETHER,
            'why_partner': WHY_PARTNER,
            'ecosystem': ECOSYSTEM,
            'partnership_models': PARTNERSHIP_MODELS,
            'open_idea': OPEN_IDEA,
            'how_it_works': HOW_IT_WORKS,
            'final_cta': FINAL_CTA,
            'social_links': SOCIAL_LINKS,
        },
    )


def robots_txt(request):
    lines = [
        'User-agent: *',
        'Allow: /',
        'Disallow: /django-admin/',
        'Disallow: /platform/',
        'Disallow: /employers/',
        'Disallow: /seekers/dashboard/',
        'Disallow: /accounts/',
        'Disallow: /api/',
        f'Sitemap: {request.build_absolute_uri("/sitemap.xml")}',
    ]
    return HttpResponse('\n'.join(lines), content_type='text/plain')


def health_check(request):
    return JsonResponse({'status': 'ok'})
