from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework import generics, permissions, status
from rest_framework.response import Response
from .serializers import ProfileSerializer, UserAddressSerializer, CustomTokenObtainPairSerializer
from .models import UserAddressModel, User
from rest_framework.permissions import IsAuthenticated, AllowAny
from drf_spectacular.utils import extend_schema, OpenApiParameter
from rest_framework_simplejwt.views import TokenObtainPairView
from django.shortcuts import get_object_or_404
from rest_framework_simplejwt.tokens import RefreshToken
import ghasedak_sms
class SendOTPView(APIView):
    permission_classes = [AllowAny]
    @extend_schema(
    tags=["Authentication"],
        request={
            "application/json": {
                "type": "object",
                "properties": {
                    "phone": {"type": "string", "example": "09123456789"},
                },
                "required": ["phone"],
            }
        },
    )
    def post(self, request):
        phone = request.data.get('phone')
        if not phone:
            return Response({'detail': 'Phone number is required'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            user, created = User.objects.get_or_create(phone=phone)
            otp = user.set_otp()  
            message = f"کد یک بار مصرف : {otp}"

            
            sms_api = ghasedak_sms.Ghasedak(api_key="4dc844abd4409fe247ec73831aed2498ad3749c1945660cc252654371756b966vafe5d9LGgMbnfGn")  

            # response = sms_api.send_single_sms(ghasedak_sms.SendSingleSmsInput(message=message, receptor=phone, line_number='30005006006908', send_date='', client_reference_id=''))
            # print(response)



            response = sms_api.send_single_sms(
                ghasedak_sms.SendSingleSmsInput(
                    message=message,
                    receptor=phone,
                    line_number='90002930',
                    send_date='',
                    client_reference_id=''
                )
            )

            # response = sms_api.send_otp_sms(otp_input)

            if response['statusCode'] == 200:  
                return Response({'detail': 'OTP sent successfully'}, status=status.HTTP_200_OK)
            else:
                print('remmber to remove #TODO')
                return Response({'detail': f'OTP sent successfully {otp}'}, status=status.HTTP_200_OK)
                # return Response({'detail': response, 'otp_code': otp}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        except User.DoesNotExist:
            return Response({'detail': 'user not found'}, status=status.HTTP_404_NOT_FOUND)
        except Exception as e:
            return Response({'detail': f'An error occurred: {response}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class CustomTokenObtainPairView(TokenObtainPairView):
    serializer_class = CustomTokenObtainPairSerializer
    @extend_schema(
        tags=["Authentication"]
    )
    def post(self, request, *args, **kwargs):
        phone = request.data.get("phone")
        otp = request.data.get("otp")
        user = get_object_or_404(User, phone=phone)
        if user:
            if not otp:
                return Response({'detail': 'کد یک بار مصرف ضروری میباشد'}, status=status.HTTP_401_UNAUTHORIZED)
            if not user.verify_otp(otp):
                return Response({'detail': 'کد یک بار مصرف منقضی شده یا اشتباه است'}, status=status.HTTP_401_UNAUTHORIZED)
            
            user.clear_otp()
            refresh = RefreshToken.for_user(user)
            return Response({
                'refresh': str(refresh),
                'access': str(refresh.access_token),
            })

        return Response({'detail': 'Invalid credentials'}, status=status.HTTP_401_UNAUTHORIZED)




class ProfileView(APIView):
    serializer_class = ProfileSerializer
    permission_classes = [IsAuthenticated]

    def get(self, request):
        user_ser = self.serializer_class(instance=request.user)
        return Response(user_ser.data, status=status.HTTP_200_OK)


    def patch(self, request):
        user = request.user
        user_ser = self.serializer_class(user, data=request.data, partial=True)
        if user_ser.is_valid():
            user_ser.save()
            return Response(user_ser.data)
        return Response(user_ser.errors, status=status.HTTP_400_BAD_REQUEST)

class CreateAddressView(generics.CreateAPIView):
    queryset = UserAddressModel.objects.all()
    serializer_class = UserAddressSerializer
    permission_classes = [permissions.IsAuthenticated]

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)

class EditAddressView(generics.UpdateAPIView):
    queryset = UserAddressModel.objects.all()
    serializer_class = UserAddressSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_queryset(self):
        return UserAddressModel.objects.filter(user=self.request.user)

class DeleteAddressView(generics.DestroyAPIView):
    queryset = UserAddressModel.objects.all()
    permission_classes = [permissions.IsAuthenticated]

    def get_queryset(self):
        return UserAddressModel.objects.filter(user=self.request.user)

class GetUserAddressesView(generics.ListAPIView):
    serializer_class = UserAddressSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_queryset(self):
        return UserAddressModel.objects.filter(user=self.request.user)

class GetIDUserAddressView(generics.RetrieveAPIView):
    serializer_class = UserAddressSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_queryset(self):
        return UserAddressModel.objects.filter(user=self.request.user)