from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.permissions import IsAuthenticated, AllowAny
from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi
from django.shortcuts import get_object_or_404
from django.db.models import Q

from service.serializers.contact_service import ContactServiceSerializer
from service.models.services import ContactServiceProvider
from common.pagination.custom_pagination import CustomPageNumberPagination


class ContactServiceProviderListCreateAPIView(APIView):
    
    def get_permissions(self):
        """Allow public POST (create), but require authentication for GET (list)"""
        if self.request.method == 'POST':
            return [AllowAny()]
        return [IsAuthenticated()]
    
    @swagger_auto_schema(request_body=ContactServiceSerializer)
    def post(self, request):
        """Public - anyone can create contact"""
        serializer = ContactServiceSerializer(data=request.data, context={'request': request})
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(
            {"success": "Contact service provider created successfully. We will get back to you soon!"}, 
            status=status.HTTP_201_CREATED
        )
    
    @swagger_auto_schema(
        operation_description="Get contact service providers based on user role and permissions",
        manual_parameters=[
            openapi.Parameter('service', openapi.IN_QUERY, description="Filter by service ID", type=openapi.TYPE_INTEGER),
            openapi.Parameter('service_name', openapi.IN_QUERY, description="Filter by service name", type=openapi.TYPE_STRING),
            openapi.Parameter('service_company', openapi.IN_QUERY, description="Filter by service company", type=openapi.TYPE_STRING),
            openapi.Parameter('service_category', openapi.IN_QUERY, description="Filter by service category ID", type=openapi.TYPE_INTEGER),
            openapi.Parameter('district', openapi.IN_QUERY, description="Filter by district", type=openapi.TYPE_STRING),
            openapi.Parameter('first_name', openapi.IN_QUERY, description="Filter by first name", type=openapi.TYPE_STRING),
            openapi.Parameter('last_name', openapi.IN_QUERY, description="Filter by last name", type=openapi.TYPE_STRING),
            openapi.Parameter('service__created_by', openapi.IN_QUERY, description="Filter by service owner ID", type=openapi.TYPE_INTEGER),
            openapi.Parameter('service__created_by__username', openapi.IN_QUERY, description="Filter by service owner username", type=openapi.TYPE_STRING),
            openapi.Parameter('service__created_by__email', openapi.IN_QUERY, description="Filter by service owner email", type=openapi.TYPE_STRING),
            openapi.Parameter('created_by', openapi.IN_QUERY, description="Filter by contact creator ID", type=openapi.TYPE_INTEGER),
            openapi.Parameter('created_by__username', openapi.IN_QUERY, description="Filter by contact creator username", type=openapi.TYPE_STRING),
            openapi.Parameter('created_by__email', openapi.IN_QUERY, description="Filter by contact creator email", type=openapi.TYPE_STRING),
            openapi.Parameter('page', openapi.IN_QUERY, description="Page number", type=openapi.TYPE_INTEGER),
            openapi.Parameter('page_size', openapi.IN_QUERY, description="Items per page", type=openapi.TYPE_INTEGER),
        ]
    )
    def get(self, request):
        """Authenticated - role-based access"""
        contacts = ContactServiceProvider.objects.filter(is_active=True).select_related(
            'service',
            'service__created_by',
            'created_by'
        ).order_by('-created_at')
        
        user = request.user
        if user.role == 'admin':
            pass
        else:
            contacts = contacts.filter(
                Q(created_by=user) |  
                Q(service__created_by=user) 
            )
        
        # Get query parameters for filtering
        service_id = request.query_params.get('service')
        service_name = request.query_params.get('service_name')
        service_company = request.query_params.get('service_company')
        service_category = request.query_params.get('service_category')
        district = request.query_params.get('district')
        first_name = request.query_params.get('first_name')
        last_name = request.query_params.get('last_name')
        service_created_by = request.query_params.get('service__created_by')
        service_created_by_username = request.query_params.get('service__created_by__username')
        service_created_by_email = request.query_params.get('service__created_by__email')
        created_by = request.query_params.get('created_by')
        created_by_username = request.query_params.get('created_by__username')
        created_by_email = request.query_params.get('created_by__email')
        
        # Apply filters
        if service_id:
            contacts = contacts.filter(service_id=service_id)
        if service_name:
            contacts = contacts.filter(service__name__icontains=service_name)
        if service_company:
            contacts = contacts.filter(service__company__icontains=service_company)
        if service_category:
            contacts = contacts.filter(service__service_category_id=service_category)
        if district:
            contacts = contacts.filter(district__icontains=district)
        if first_name:
            contacts = contacts.filter(first_name__icontains=first_name)
        if last_name:
            contacts = contacts.filter(last_name__icontains=last_name)
        if service_created_by:
            contacts = contacts.filter(service__created_by_id=service_created_by)
        if service_created_by_username:
            contacts = contacts.filter(service__created_by__username__icontains=service_created_by_username)
        if service_created_by_email:
            contacts = contacts.filter(service__created_by__email__icontains=service_created_by_email)
        if created_by:
            contacts = contacts.filter(created_by_id=created_by)
        if created_by_username:
            contacts = contacts.filter(created_by__username__icontains=created_by_username)
        if created_by_email:
            contacts = contacts.filter(created_by__email__icontains=created_by_email)
        
        paginator = CustomPageNumberPagination()
        result_page = paginator.paginate_queryset(contacts, request)
        serializer = ContactServiceSerializer(result_page, many=True, context={'request': request})
        return paginator.get_paginated_response(serializer.data)


class ContactServiceProviderDetailAPIView(APIView):
    permission_classes = [IsAuthenticated]
    
    @swagger_auto_schema(request_body=ContactServiceSerializer)
    def put(self, request, pk):
        contact = get_object_or_404(ContactServiceProvider, pk=pk)
        serializer = ContactServiceSerializer(contact, data=request.data, context={'request': request})
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"success": "Contact service provider updated successfully"}, status=status.HTTP_200_OK)

    def get(self, request, pk):
        contact = get_object_or_404(ContactServiceProvider, pk=pk)
        serializer = ContactServiceSerializer(contact, context={'request': request})
        return Response(serializer.data)

    def delete(self, request, pk):
        contact = get_object_or_404(ContactServiceProvider, pk=pk)
        contact.soft_delete()
        return Response({"success": "Contact service provider deleted successfully"}, status=status.HTTP_200_OK)