from rest_framework import generics, status
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.parsers import MultiPartParser, FormParser, JSONParser

# Import models & serializers
from core.models import SiteSettings, SocialLink, SEOData
from core.serializers import SiteSettingsSerializer, SocialLinkSerializer, SEODataSerializer

from pages.models import HeroSlide, CompanyStat, WhyChooseUs
from pages.serializers import HeroSlideSerializer, CompanyStatSerializer, WhyChooseUsSerializer

from services.models import Service, ServiceCategory
from services.serializers import ServiceSerializer, ServiceCategorySerializer

from portfolio.models import Project, ProjectCategory, Technology
from portfolio.serializers import ProjectSerializer, ProjectCategorySerializer, TechnologySerializer

from blog.models import BlogPost, BlogCategory
from blog.serializers import BlogPostSerializer, BlogCategorySerializer

from careers.models import Job, JobApplication
from careers.serializers import JobSerializer, JobApplicationSerializer

from contact.models import ContactMessage, ProjectInquiry
from contact.serializers import ContactMessageSerializer, ProjectInquirySerializer

from team.models import TeamMember
from team.serializers import TeamMemberSerializer

from testimonials.models import Testimonial
from testimonials.serializers import TestimonialSerializer

from newsletter.models import NewsletterSubscriber
from newsletter.serializers import NewsletterSubscriberSerializer

from faqs.models import FAQ, FAQCategory
from faqs.serializers import FAQSerializer, FAQCategorySerializer


class SiteSettingsView(APIView):
    def get(self, request):
        settings = SiteSettings.objects.first()
        if not settings:
            settings = SiteSettings.objects.create()
        return Response(SiteSettingsSerializer(settings).data)


class SocialLinkListView(generics.ListAPIView):
    queryset = SocialLink.objects.filter(is_active=True).order_by('order')
    serializer_class = SocialLinkSerializer


class SEODataListView(generics.ListAPIView):
    queryset = SEOData.objects.all()
    serializer_class = SEODataSerializer


class HeroSlideListView(generics.ListAPIView):
    queryset = HeroSlide.objects.filter(is_active=True).order_by('order')
    serializer_class = HeroSlideSerializer


class CompanyStatListView(generics.ListAPIView):
    queryset = CompanyStat.objects.all().order_by('order')
    serializer_class = CompanyStatSerializer


class WhyChooseUsListView(generics.ListAPIView):
    queryset = WhyChooseUs.objects.all().order_by('order')
    serializer_class = WhyChooseUsSerializer


class ServiceListView(generics.ListAPIView):
    serializer_class = ServiceSerializer

    def get_queryset(self):
        queryset = Service.objects.filter(is_active=True).order_by('order')
        category_slug = self.request.query_params.get('category')
        if category_slug:
            queryset = queryset.filter(category__slug=category_slug)
        return queryset


class ServiceDetailView(generics.RetrieveAPIView):
    queryset = Service.objects.filter(is_active=True)
    serializer_class = ServiceSerializer
    lookup_field = 'slug'


class ServiceCategoryListView(generics.ListAPIView):
    queryset = ServiceCategory.objects.all()
    serializer_class = ServiceCategorySerializer


class ProjectListView(generics.ListAPIView):
    serializer_class = ProjectSerializer

    def get_queryset(self):
        queryset = Project.objects.all().order_by('order', '-id')
        category_slug = self.request.query_params.get('category')
        if category_slug:
            queryset = queryset.filter(category__slug=category_slug)
        featured = self.request.query_params.get('featured')
        if featured == 'true':
            queryset = queryset.filter(is_featured=True)
        return queryset


class ProjectDetailView(generics.RetrieveAPIView):
    queryset = Project.objects.all()
    serializer_class = ProjectSerializer
    lookup_field = 'slug'


class ProjectCategoryListView(generics.ListAPIView):
    queryset = ProjectCategory.objects.all()
    serializer_class = ProjectCategorySerializer


class TechnologyListView(generics.ListAPIView):
    queryset = Technology.objects.all()
    serializer_class = TechnologySerializer


class BlogPostListView(generics.ListAPIView):
    serializer_class = BlogPostSerializer

    def get_queryset(self):
        queryset = BlogPost.objects.filter(status='published').order_by('-published_at')
        category_slug = self.request.query_params.get('category')
        search = self.request.query_params.get('search')
        if category_slug:
            queryset = queryset.filter(category__slug=category_slug)
        if search:
            queryset = queryset.filter(title__icontains=search) | queryset.filter(summary__icontains=search)
        return queryset


class BlogPostDetailView(generics.RetrieveAPIView):
    queryset = BlogPost.objects.filter(status='published')
    serializer_class = BlogPostSerializer
    lookup_field = 'slug'


class BlogCategoryListView(generics.ListAPIView):
    queryset = BlogCategory.objects.all()
    serializer_class = BlogCategorySerializer


class JobListView(generics.ListAPIView):
    queryset = Job.objects.filter(is_active=True).order_by('-created_at')
    serializer_class = JobSerializer


class JobDetailView(generics.RetrieveAPIView):
    queryset = Job.objects.filter(is_active=True)
    serializer_class = JobSerializer
    lookup_field = 'slug'


class JobApplicationCreateView(APIView):
    parser_classes = [MultiPartParser, FormParser, JSONParser]

    def post(self, request):
        serializer = JobApplicationSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response({
                "success": True,
                "message": "Your job application has been successfully submitted. The SONICTECH recruitment team will review your profile.",
                "data": serializer.data
            }, status=status.HTTP_201_CREATED)
        return Response({"success": False, "errors": serializer.errors}, status=status.HTTP_400_BAD_REQUEST)


class ContactMessageCreateView(APIView):
    def post(self, request):
        serializer = ContactMessageSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response({
                "success": True,
                "message": "Thank you for contacting SONICTECH. Your inquiry has been received and our team will get back to you within 24 hours.",
                "data": serializer.data
            }, status=status.HTTP_201_CREATED)
        return Response({"success": False, "errors": serializer.errors}, status=status.HTTP_400_BAD_REQUEST)


class ProjectInquiryCreateView(APIView):
    parser_classes = [MultiPartParser, FormParser, JSONParser]

    def post(self, request):
        serializer = ProjectInquirySerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response({
                "success": True,
                "message": "Your project quote request has been successfully received. A senior solutions architect will contact you shortly.",
                "data": serializer.data
            }, status=status.HTTP_201_CREATED)
        return Response({"success": False, "errors": serializer.errors}, status=status.HTTP_400_BAD_REQUEST)


class TeamMemberListView(generics.ListAPIView):
    queryset = TeamMember.objects.all().order_by('order', 'name')
    serializer_class = TeamMemberSerializer


class TestimonialListView(generics.ListAPIView):
    queryset = Testimonial.objects.filter(is_active=True).order_by('order', '-id')
    serializer_class = TestimonialSerializer


class NewsletterSubscribeView(APIView):
    def post(self, request):
        email = request.data.get('email')
        if not email:
            return Response({"success": False, "message": "A valid email address is required."}, status=status.HTTP_400_BAD_REQUEST)
        
        subscriber, created = NewsletterSubscriber.objects.get_or_create(email=email)
        if not created and not subscriber.is_active:
            subscriber.is_active = True
            subscriber.save()
            
        return Response({
            "success": True,
            "message": "Thank you for subscribing to SONICTECH's technology insights newsletter."
        }, status=status.HTTP_200_OK)


class FAQListView(generics.ListAPIView):
    queryset = FAQ.objects.filter(is_active=True).order_by('order', 'id')
    serializer_class = FAQSerializer


class FAQCategoryListView(generics.ListAPIView):
    queryset = FAQCategory.objects.all().order_by('order')
    serializer_class = FAQCategorySerializer
