from rest_framework import generics, status, permissions
from rest_framework.response import Response
from rest_framework.authtoken.models import Token
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny, IsAuthenticated
from django.contrib.auth import authenticate
from common.response_helper import ResponseHelper
from .models import Rider
from .serializers import (
    RiderRegistrationSerializer, 
    RiderLoginSerializer, 
    RiderProfileSerializer,
    RiderUpdateSerializer,
    RiderPasswordChangeSerializer
)


class RiderRegistrationView(generics.CreateAPIView):
    """API view for rider registration"""
    serializer_class = RiderRegistrationSerializer
    permission_classes = [AllowAny]

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            rider = serializer.save()
            
            # Create authentication token
            refresh = RefreshToken.for_user(rider.user)
            
            # Prepare response data
            profile_serializer = RiderProfileSerializer(rider)
            response_data = {
                'rider': profile_serializer.data,
                'refresh': str(refresh),
                'access': str(refresh.access_token),
                'message': 'Rider registration successful'
            }
            
            return ResponseHelper.success(
                data=response_data,
                message='Registration successful',
                status=status.HTTP_201_CREATED
            )
        
        return ResponseHelper.error(
            errors=serializer.errors,
            message='Registration failed',
            status=status.HTTP_400_BAD_REQUEST
        )


class RiderLoginView(generics.GenericAPIView):
    """API view for rider login"""
    serializer_class = RiderLoginSerializer
    permission_classes = [AllowAny]

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            user = serializer.validated_data['user']
            rider = serializer.validated_data['rider']
            
            # Get or create authentication token
            refresh = RefreshToken.for_user(user)
            
            # Prepare minimal response data (limit fields for login)
            rider_data = {
                'id': rider.id,
                'full_name': rider.full_name,
                'display_name': rider.display_name,
                'email': rider.email,
                'phone': rider.mobile_number,
                'status': rider.status,
            }

            response_data = {
                'rider': rider_data,
                'refresh': str(refresh),
                'access': str(refresh.access_token),
                'message': 'Login successful'
            }

            return ResponseHelper.success(
                data=response_data,
                message='Login successful',
                status=status.HTTP_200_OK
            )
        
        return ResponseHelper.error(
            errors=serializer.errors,
            message='Login failed',
            status=status.HTTP_400_BAD_REQUEST
        )


class RiderProfileView(generics.RetrieveAPIView):
    """API view for getting rider profile"""
    serializer_class = RiderProfileSerializer
    permission_classes = [IsAuthenticated]

    def get_object(self):
        """Get rider profile for authenticated user"""
        try:
            return self.request.user.rider_profile
        except Rider.DoesNotExist:
            return None

    def retrieve(self, request, *args, **kwargs):
        rider = self.get_object()
        if not rider:
            return ResponseHelper.error(
                message='Rider profile not found',
                status=status.HTTP_404_NOT_FOUND
            )
        
        serializer = self.get_serializer(rider)
        return ResponseHelper.success(
            data={'rider': serializer.data},
            message='Profile retrieved successfully'
        )


class RiderUpdateView(generics.UpdateAPIView):
    """API view for updating rider profile"""
    serializer_class = RiderUpdateSerializer
    permission_classes = [IsAuthenticated]

    def get_object(self):
        """Get rider profile for authenticated user"""
        try:
            return self.request.user.rider_profile
        except Rider.DoesNotExist:
            return None

    def update(self, request, *args, **kwargs):
        rider = self.get_object()
        if not rider:
            return ResponseHelper.error(
                message='Rider profile not found',
                status=status.HTTP_404_NOT_FOUND
            )

        serializer = self.get_serializer(rider, data=request.data, partial=True)
        if serializer.is_valid():
            updated_rider = serializer.save()
            
            # Return updated profile
            profile_serializer = RiderProfileSerializer(updated_rider)
            return ResponseHelper.success(
                data={'rider': profile_serializer.data},
                message='Profile updated successfully'
            )
        
        return ResponseHelper.error(
            errors=serializer.errors,
            message='Profile update failed',
            status=status.HTTP_400_BAD_REQUEST
        )


class RiderPasswordChangeView(generics.GenericAPIView):
    """API view for changing rider password"""
    serializer_class = RiderPasswordChangeSerializer
    permission_classes = [IsAuthenticated]

    def post(self, request, *args, **kwargs):
        # Check if user has rider profile
        try:
            request.user.rider_profile
        except Rider.DoesNotExist:
            return ResponseHelper.error(
                message='Rider profile not found',
                status=status.HTTP_404_NOT_FOUND
            )

        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return ResponseHelper.success(
                message='Password changed successfully'
            )
        
        return ResponseHelper.error(
            errors=serializer.errors,
            message='Password change failed',
            status=status.HTTP_400_BAD_REQUEST
        )


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def rider_logout(request):
    """API view for rider logout"""
    try:
        # Check if user has rider profile
        request.user.rider_profile
    except Rider.DoesNotExist:
        return ResponseHelper.error(
            message='Rider profile not found',
            status=status.HTTP_404_NOT_FOUND
        )
    
    try:
        # Delete the user's auth token
        token = Token.objects.get(user=request.user)
        token.delete()
        
        return ResponseHelper.success(
            message='Logout successful'
        )
    except Token.DoesNotExist:
        return ResponseHelper.error(
            message='Token not found',
            status=status.HTTP_400_BAD_REQUEST
        )


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def rider_status_check(request):
    """API view to check rider account status"""
    try:
        rider = request.user.rider_profile
        
        response_data = {
            'is_active': rider.status == 'active',
            'is_trashed': rider.trash,
            'status': rider.status
        }
        
        return ResponseHelper.success(
            data=response_data,
            message='Status check successful'
        )
    except Rider.DoesNotExist:
        return ResponseHelper.error(
            message='Rider profile not found',
            status=status.HTTP_404_NOT_FOUND
        )