import json
import random
from django.conf import settings
from rest_framework import status
from django.http import JsonResponse
from rest_framework.response import Response
from .models import Users
from .auth import generate_access_token
from rest_framework.views import APIView
from rest_framework.decorators import api_view
from django.db.models import Q, Avg
from utils.helpers import verify_token, send_otp_to_phone
from django.shortcuts import get_object_or_404
from .serializers import ProfessionalSerializer, ProfessionalsSerializer, UserProfileSerializer


class SendOtp(APIView):
    def post(self, request):
        request_data = json.loads(request.body)
        mobile = request_data['mobile']
        otp = str(random.randint(1000, 9999))
        # otp = "1234"
        print(otp)
        result = send_otp_to_phone(mobile, otp)
        if result == True:
            request.session['mobile'] = mobile
            request.session['otp'] = otp
            return JsonResponse({'message' : "OTP send your mobile phone successfully", 'status':status.HTTP_200_OK}, safe=False, status=status.HTTP_200_OK)
        else :
            return JsonResponse({'message' : "OTP not send your mobile phone. Please try again later.", 'status':status.HTTP_400_BAD_REQUEST}, safe=False, status=status.HTTP_400_BAD_REQUEST)



class VerifyOtp(APIView):
    def post(self, request):
        try:
            request_data = json.loads(request.body)
            otp = request_data['otp']
            if otp == request.session['otp']:
                try:
                    user = Users.objects.get(mobile = request.session['mobile'], user_type = 2)
                    if user.user_type == 2:
                        user.fcm_token = request_data['fcm_token']
                        user.save()
                        access_token = generate_access_token(user)
                        return JsonResponse({'message' : "Login successfully", "user_id":user.id, 'token' : access_token, 'mobile' : user.mobile, 'status':status.HTTP_200_OK}, safe=False, status=status.HTTP_200_OK)
                    else:
                        return JsonResponse({'message' : "Designer Account with this mobile no. already exists. Please use different one.", 'status':status.HTTP_400_BAD_REQUEST}, safe=False, status=status.HTTP_400_BAD_REQUEST)
                except Users.DoesNotExist:
                    user = Users()
                    username = ''.join((random.choice('1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ') for i in range(6)))
                    user.username = 'user-' + username
                    user.is_active = 1
                    user.is_superuser = 0
                    user.user_type = 2
                    user.is_staff = 0
                    user.mobile = request.session['mobile']
                    user.fcm_token = request_data['fcm_token']
                    user.save()
                    access_token = generate_access_token(user)
                    return Response({'message' : "Login successfully", 'token' : access_token, 'status':status.HTTP_200_OK})
            else:
                return Response({'message' : "Invalid OTP.", 'status':status.HTTP_400_BAD_REQUEST})
        except Exception as e:
            print(e)
            return Response({'message' : "Something went wrong. Please try again later.", 'status':status.HTTP_400_BAD_REQUEST})
       


@api_view(['get'])
def verifyUser(request):
    user = verify_token(request)
    if user == None:
        return Response({'message' : "User not logged in", 'status':status.HTTP_401_UNAUTHORIZED})
    else:
        try:
            user = Users.objects.get(id = user)
            return Response({'message' : "User logged in", 'name' : user.name, 'id' : user.id, 'profile_pic' : str(user.profile_pic), 'email' : user.email, 'mobile' : user.mobile, 'status':status.HTTP_200_OK})
        except Exception as e:
           print(e)
           return Response({'message' : "User not logged in", 'status':status.HTTP_401_UNAUTHORIZED})




class UserProfile(APIView):

    def get(self, request):

        user_id = verify_token(request)

        if not user_id:
            return Response(
                {
                    "message": "User not logged in",
                    "status": status.HTTP_401_UNAUTHORIZED
                },
                status=status.HTTP_401_UNAUTHORIZED
            )

        try:
            user = Users.objects.get(id=user_id)

            serializer = UserProfileSerializer(
                user,
                context={'request': request}
            )

            return Response(
                {
                    "profile": serializer.data,
                    "status": status.HTTP_200_OK
                },
                status=status.HTTP_200_OK
            )

        except Users.DoesNotExist:
            return Response(
                {
                    "message": "User not found",
                    "status": status.HTTP_404_NOT_FOUND
                },
                status=status.HTTP_404_NOT_FOUND
            )

        except Exception as e:
            print(e)

            return Response(
                {
                    "message": "Something went wrong",
                    "status": status.HTTP_500_INTERNAL_SERVER_ERROR
                },
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )
        

    def post(self, request):

        user_id = verify_token(request)
        print(request.data)
        if not user_id:
            return Response(
                {
                    "message": "User not logged in",
                    "status": status.HTTP_401_UNAUTHORIZED
                },
                status=status.HTTP_401_UNAUTHORIZED
            )

        try:
            user = Users.objects.get(id=user_id)

            user.name = request.data.get('name', user.name)
            user.email = request.data.get('email', user.email)
            user.mobile = request.data.get('mobile', user.mobile)
            user.address = request.data.get('address', user.address)

            if request.FILES.get('profile_pic'):
                user.profile_pic = request.FILES.get('profile_pic')

            user.save()

            return Response(
                {
                    "message": "Profile updated successfully",
                    "status": status.HTTP_200_OK
                },
                status=status.HTTP_200_OK
            )

        except Users.DoesNotExist:
            return Response(
                {
                    "message": "User not found",
                    "status": status.HTTP_404_NOT_FOUND
                },
                status=status.HTTP_404_NOT_FOUND
            )

        except Exception as e:
            print(e)

            return Response(
                {
                    "message": "Something went wrong",
                    "status": status.HTTP_500_INTERNAL_SERVER_ERROR
                },
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )
        


class AccountsProfessionalsView(APIView):

    def get(self, request):

        try:

            search = request.GET.get("search", "")
            sub_category_id = request.GET.get("sub_category_id", None)

            queryset = Users.objects.filter(
                contractor_profile__isnull=False,
                contractor_profile__is_verified = 1
            ).select_related(
                "contractor_profile"
            ).prefetch_related(
                "contractor_profile__sub_categories"
            ).annotate(
                avg_rating=Avg(
                    "work_sub_category_contractor__rating",
                    filter=Q(work_sub_category_contractor__rating__gt=0)
                )
            ).distinct()

            # -------------------------
            # FILTER BY SUB CATEGORY
            # -------------------------
            if sub_category_id:
                queryset = queryset.filter(
                    contractor_profile__sub_categories__id=sub_category_id
                )

            # -------------------------
            # SEARCH FILTER
            # -------------------------
            if search:
                queryset = queryset.filter(
                    name__icontains=search
                )

            serializer = ProfessionalsSerializer(queryset, many=True)

            return Response({
                "status": 200,
                "professionals": serializer.data
            })

        except Exception as e:
            return Response({
                "status": 500,
                "message": str(e)
            })
        


class AccountsProfessionalView(APIView):

    def get(self, request):

        try:
            user_id = request.GET.get("user_id")

            if not user_id:
                return Response({
                    "status": 400,
                    "message": "user_id is required"
                })

            user = get_object_or_404(
                Users.objects.select_related("contractor_profile"),
                id=user_id
            )

            serializer = ProfessionalSerializer(user)
            
            return Response({
                "status": 200,
                "profile": serializer.data
            })

        except Exception as e:
            return Response({
                "status": 500,
                "message": str(e)
            })