from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.pagination import PageNumberPagination
from rest_framework.exceptions import ValidationError, NotFound
from drf_yasg.utils import swagger_auto_schema
from django.shortcuts import get_object_or_404
from rest_framework.permissions import IsAuthenticated

from api.property_api.contact_information.models.contact_information import ContactInformation
from api.property_api.contact_information.serializers.contact_information_serializer import ContactInformationSerializer

from drf_yasg import openapi

from django.db.models import Q

class ContactInformationListCreateAPIView(APIView):
    
    @swagger_auto_schema(request_body=ContactInformationSerializer)
    def post(self, request):
        serializer = ContactInformationSerializer(data=request.data, context={'request': request})
        serializer.is_valid(raise_exception=True)
        if request.user.is_authenticated:
            serializer.save(created_by=request.user)
        else:
            serializer.save()
        return Response({"success": "Contact Information created successfully"}, status=status.HTTP_201_CREATED)
    
    @swagger_auto_schema(
        operation_description="Get contact information list with optional filters",
        manual_parameters=[
            openapi.Parameter('property', openapi.IN_QUERY, description="Filter by property ID", type=openapi.TYPE_INTEGER),
            openapi.Parameter('property_name', openapi.IN_QUERY, description="Filter by property name", type=openapi.TYPE_STRING),
            openapi.Parameter('property_type', openapi.IN_QUERY, description="Filter by property type", type=openapi.TYPE_STRING),
            openapi.Parameter('property__created_by', openapi.IN_QUERY, description="Filter by property creator ID", type=openapi.TYPE_INTEGER),
            openapi.Parameter('property__created_by__username', openapi.IN_QUERY, description="Filter by property creator username", type=openapi.TYPE_STRING),
            openapi.Parameter('property__created_by__email', openapi.IN_QUERY, description="Filter by property creator email", type=openapi.TYPE_STRING),
            openapi.Parameter('created_by', openapi.IN_QUERY, description="Filter by contact information creator ID", type=openapi.TYPE_INTEGER),
            openapi.Parameter('created_by__username', openapi.IN_QUERY, description="Filter by creator username", type=openapi.TYPE_STRING),
            openapi.Parameter('created_by__email', openapi.IN_QUERY, description="Filter by 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="Number of items per page", type=openapi.TYPE_INTEGER),
        ]
    )
    def get(self, request):
        if not request.user.is_authenticated:
            return Response(
                {"error": "Authentication required"}, 
                status=status.HTTP_401_UNAUTHORIZED
            )
        infos = ContactInformation.objects.filter(is_active=True).select_related(
            'property',
            'property__created_by',
            'created_by'
        ).order_by('-created_at')
        
        user = request.user
        if user.role == 'admin':
            pass
        else:
            infos = infos.filter(
                Q(created_by=user) |  
                Q(property__created_by=user)  
            )
        
        # Get query parameters for filtering
        property_id = request.query_params.get('property')
        property_name = request.query_params.get('property_name')
        property_type = request.query_params.get('property_type')
        property_created_by = request.query_params.get('property__created_by')
        property_created_by_username = request.query_params.get('property__created_by__username')
        property_created_by_email = request.query_params.get('property__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 property_id:
            infos = infos.filter(property_id=property_id)
        
        if property_name:
            infos = infos.filter(property__name__icontains=property_name)
        
        if property_type:
            infos = infos.filter(property__type__iexact=property_type)
        
        if property_created_by:
            infos = infos.filter(property__created_by_id=property_created_by)
        
        if property_created_by_username:
            infos = infos.filter(property__created_by__username__icontains=property_created_by_username)
        
        if property_created_by_email:
            infos = infos.filter(property__created_by__email__icontains=property_created_by_email)
        
        if created_by:
            infos = infos.filter(created_by_id=created_by)
        
        if created_by_username:
            infos = infos.filter(created_by__username__icontains=created_by_username)
        
        if created_by_email:
            infos = infos.filter(created_by__email__icontains=created_by_email)
        
        paginator = PageNumberPagination()
        result_page = paginator.paginate_queryset(infos, request)
        serializer = ContactInformationSerializer(result_page, many=True, context={'request': request})
        return paginator.get_paginated_response(serializer.data)
        
class ContactInformationDetailAPIView(APIView):
    @swagger_auto_schema(request_body=ContactInformationSerializer)
    def put(self, request, pk):
        infos = get_object_or_404(ContactInformation, pk=pk)
        serializer = ContactInformationSerializer(infos, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"success": "Contact Information updated successfully"}, status=status.HTTP_200_OK)

    def get(self, request, pk):
        infos = get_object_or_404(ContactInformation, pk=pk)
        serializer = ContactInformationSerializer(infos)
        return Response(serializer.data)

    def delete(self, request, pk):
        infos = get_object_or_404(ContactInformation, pk=pk)
        infos.soft_delete()
        return Response({"success": "Contact Information deleted successfully"}, status=status.HTTP_200_OK)
    