from django.shortcuts import render

from wagtail.api.v2.router import WagtailAPIRouter
from wagtail.api.v2.views import PagesAPIViewSet, BaseAPIViewSet
# Create your views here.
from .models import *

from datetime import datetime


def service_detail(request, category_slug, service_slug):
    return render(request, 'index.html', )


class HeaderAPIEndpoint(BaseAPIViewSet):
    model = Header
    body_fields = ['title', 'fontType', 'size', 'content','iconBG','iconFG','iconHoverBG','iconHoverFG','icon','shape']
    listing_default_fields = body_fields
    


class WebPageView(PagesAPIViewSet):
    model = WebPage
    body_fields = ['title','slug', 'body','bannercontent' ]
    listing_default_fields = body_fields
    def serialize_bannercontent(self, page):
        return serialize_bannercontent(page.bannercontent)

    def to_representation(self, instance):
        data = super().to_representation(instance)
        data['bannercontent'] = self.serialize_bannercontent(instance)
        return data

    
    # def get(self, request, slug, format=None):
    #     obj = WebPage.objects.get(slug=slug)
    #     serializer = WebPageSerializer(obj)
    #     return Response(serializer.data)


from django.contrib.auth import get_user_model
CustomUser = get_user_model()
from rest_framework.views import APIView
from rest_framework import permissions
from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated, IsAdminUser, DjangoModelPermissions
from django.db.models import Sum, F
from django.shortcuts import get_object_or_404
from django.db import IntegrityError

from django.db.models import Q
from .serializers import *
from useraccess.views import IsOwnerOrAdmin
# Create your views here.

from rest_framework.pagination import PageNumberPagination

class MyModelPagination(PageNumberPagination):
    page_size = 12
    page_size_query_param = 'page_size'
    max_page_size = 100

class FooterAPIEndpoint(BaseAPIViewSet):
    model = Footer
    body_fields = ['title', 'body']
    listing_default_fields = ['title', 'body']
    
class BottomFooterAPIEndpoint(BaseAPIViewSet):
    model = BottomFooter
    body_fields = ['bgColor', 'fgColor','fontType','size','content']
    listing_default_fields = body_fields

class ServiceCatViewSet(viewsets.ModelViewSet):
    # queryset = ServiceCat.objects.all()
    queryset = ServiceCat.objects.select_related('image').all()
    serializer_class = ServiceCatSerializer


class PolicyView(APIView):
    def get(self, request,slug, format=None):
        # obj = Policy.objects.get(slug=slug)
        obj = get_object_or_404(
            Policy.objects.only('id', 'title', 'slug', 'detail'), slug=slug
        )
        serializer = PolicySerializer(obj) 
        return Response(serializer.data)


class IndustryView(APIView):
    def get(self, request, format=None):
        obj = Industry.objects.select_related('industryImage').all()
        serializer = IndustrySerializer(obj, many=True)  # <- Tell the serializer it's a list
        return Response(serializer.data)

# class ServiceSubCatView(APIView):
#     def get(self, request, slug, format=None):
#         obj = ServiceSubCat.objects.filter(cat__slug=slug)
#         serializer = ServiceSubCatSerializer(obj, many=True)  # <- Tell the serializer it's a list
#         return Response(serializer.data)

class ServiceListView(APIView):
    def get(self, request, format=None):
        obj = Services.objects.select_related('image').all()
        serializer = ServiceSerializer(obj, many=True)  # <- Tell the serializer it's a list
        return Response(serializer.data)

class ServiceView(APIView): #List View Cat wise
    def get(self, request, slug, format=None):
        obj = Services.objects.select_related('image').filter(cat__slug=slug)
        serializer = ServiceSerializer(obj, many=True)  # <- Tell the serializer it's a list
        return Response(serializer.data)

class ServiceDetailView(APIView): #List View Cat wise
    def get(self, request, slug, format=None):
        obj = Services.objects.select_related('image').get(slug=slug)
        serializer = ServiceDetailSerializer(obj)  # <- Tell the serializer it's a list
        return Response(serializer.data)

class BottomFooterView(APIView):
    def get(self, request, format=None):
        obj = BottomFooter.objects.first()
        serializer = BottomFooterSerializer(obj)  # <- Tell the serializer it's a list
        return Response(serializer.data)

class CompanyView(APIView):
    def get(self, request, format=None):
        obj = Company.objects.first()
        serializer = CompanySerializer(obj)  # <- Tell the serializer it's a list
        return Response(serializer.data)

class EnquiryDoneView(APIView):
    permission_classes = [permissions.IsAuthenticated]
    def get(self, request,id, format=None):
        obj = Enquiry.objects.get(id=id)
        obj.enqStatus="Done"
        obj.save()
        serializer = EnquiryDetailSerializer(obj) 
        return Response(serializer.data)
    
class EnquiryDetailView(APIView):
    permission_classes = [permissions.IsAuthenticated]
    def get(self, request,id, format=None):
        obj = Enquiry.objects.get(id=id)
        serializer = EnquiryDetailSerializer(obj)  # <- Tell the serializer it's a list
        return Response(serializer.data)
    def put(self, request,id, format=None):
        obj = Enquiry.objects.get(id=id)
        FollowUp.objects.create(
            enquiry=obj,
            detail=request.data['followUp']
        )
        obj.enqStatus="Follow up"
        obj.save()
        serializer = EnquirySerializer(obj)  # <- Tell the serializer it's a list
        return Response(serializer.data)
    
    def delete(self, request, id, format=None):
        obj = get_object_or_404(Enquiry, id=id)
        obj.delete()
        return Response({'detail': 'Enquiry deleted successfully.'}, status=status.HTTP_204_NO_CONTENT)

class EnquiryListView(APIView):
    permission_classes = [permissions.IsAuthenticated]
    def get(self, request, format=None):
        obj = Enquiry.objects.all()
        
        # Search filter
        
        # Efficient Search Filter with better handling of date formatting
        query = request.query_params.get('q')
        if query:
            try:
                obj = obj.filter(
                    Q(enqName__icontains=query) |
                    Q(enqEmail__icontains=query) |
                    Q(enqContact__icontains=query) |
                    Q(enqCompany__icontains=query) |
                    Q(enqStatus__icontains=query) |
                    Q(enqCreatedOn=datetime.strptime(query, "%d-%m-%Y").date())
                )
            except ValueError:
                obj = obj.filter(
                    Q(enqName__icontains=query) |
                    Q(enqEmail__icontains=query) |
                    Q(enqContact__icontains=query) |
                    Q(enqCompany__icontains=query) |
                    Q(enqStatus__icontains=query) 
                )

          
        paginator = MyModelPagination()
        result_page = paginator.paginate_queryset(obj, request)
        serializer = EnquirySerializer(result_page, many=True)  # <- Tell the serializer it's a list
        # serializer = DealSerializer(result_page, many=True)
        return paginator.get_paginated_response(serializer.data)

class MenuItemsView(APIView):
    def get(self, request,slug, format=None):
        obj = MenuItem.objects.filter(menu__slug=slug)
        serializer = MenuItemSerializer(obj, many=True)  # <- Tell the serializer it's a list
        return Response(serializer.data)

      



class EnquiryView(APIView):
   def post(self, request, format=None):
        data=request.data
        obj = Enquiry.objects.create(
            enqName=data['selectedName'],
            enqEmail=data['selectedEmail'],
            enqContact=data['selectedContact'],
            enqCompany=data['company'],
            enqMessage=data['selectedMsg']
        )
        serializer = EnquirySerializer(obj)  # <- Tell the serializer it's a list
        return Response(serializer.data,status=status.HTTP_201_CREATED)



