from rest_framework import serializers
from django.contrib.auth import get_user_model
from .models import Rider

User = get_user_model()


class RiderRegistrationSerializer(serializers.ModelSerializer):
    """Serializer for rider registration"""
    password = serializers.CharField(write_only=True, min_length=8)
    confirm_password = serializers.CharField(write_only=True)
    
    class Meta:
        model = Rider
        fields = [
            'full_name', 'display_name', 'dob', 'mobile_number', 'email',
            'profile_pic', 'aadhar_front', 'aadhar_back', 'pan_card_image',
            'driving_license_front', 'driving_license_back', 'password', 'confirm_password'
        ]
        extra_kwargs = {
            'email': {'required': True},
            'mobile_number': {'required': True},
            'dob': {'required': True},
            'aadhar_front': {'required': True},
            'aadhar_back': {'required': True},
            'pan_card_image': {'required': True},
            'driving_license_front': {'required': True},
            'driving_license_back': {'required': True},
        }

    def validate(self, attrs):
        """Validate password confirmation"""
        if attrs['password'] != attrs['confirm_password']:
            raise serializers.ValidationError("Password and confirm password do not match.")
        return attrs

    def validate_email(self, value):
        """Check if email already exists"""
        if User.objects.filter(email=value).exists():
            raise serializers.ValidationError("A user with this email already exists.")
        return value

    def validate_mobile_number(self, value):
        """Check if mobile number already exists"""
        if Rider.objects.filter(mobile_number=value).exists():
            raise serializers.ValidationError("A rider with this mobile number already exists.")
        return value

    def create(self, validated_data):
        """Create user and rider profile"""
        password = validated_data.pop('password')
        validated_data.pop('confirm_password')
        
        # Create user account
        user = User.objects.create_user(
            username=validated_data['email'],
            email=validated_data['email'],
            password=password,
            role='RIDER'
        )
        
        # Create or update rider profile
        # The post_save signal on User might have already created the Rider profile
        try:
            rider = Rider.objects.get(user=user)
            for attr, value in validated_data.items():
                setattr(rider, attr, value)
            rider.save()
        except Rider.DoesNotExist:
            rider = Rider.objects.create(user=user, **validated_data)
            
        return rider


class RiderLoginSerializer(serializers.Serializer):
    """Serializer for rider login"""
    email = serializers.EmailField()
    password = serializers.CharField(write_only=True)

    def validate(self, attrs):
        from django.contrib.auth import authenticate
        
        email = attrs.get('email')
        password = attrs.get('password')
        
        if email and password:
            # Try to authenticate with email as username
            user = authenticate(username=email, password=password)
            
            if not user:
                raise serializers.ValidationError('Invalid email or password.')
            
            if not user.is_active:
                raise serializers.ValidationError('User account is disabled.')
            
            if user.role != 'RIDER':
                raise serializers.ValidationError('Invalid credentials for rider login.')
                
            # Check if rider profile exists
            try:
                rider = user.rider_profile
                if rider.status != 'active':
                    raise serializers.ValidationError('Rider account is not active.')
                if rider.trash:
                    raise serializers.ValidationError('Rider account has been deactivated.')
            except Rider.DoesNotExist:
                raise serializers.ValidationError('Rider profile not found.')
            
            attrs['user'] = user
            attrs['rider'] = rider
            return attrs
        else:
            raise serializers.ValidationError('Email and password are required.')


class RiderProfileSerializer(serializers.ModelSerializer):
    """Serializer for rider profile display"""
    user_email = serializers.CharField(source='user.email', read_only=True)
    user_username = serializers.CharField(source='user.username', read_only=True)
    
    class Meta:
        model = Rider
        fields = [
            'id', 'full_name', 'display_name', 'dob', 'mobile_number', 
            'email', 'profile_pic', 'aadhar_front', 'aadhar_back', 
            'pan_card_image', 'driving_license_front', 'driving_license_back',
            'status', 'created_at', 'updated_at', 'user_email', 'user_username'
        ]
        read_only_fields = ['id', 'status', 'created_at', 'updated_at']


class RiderUpdateSerializer(serializers.ModelSerializer):
    """Serializer for rider profile update"""
    
    class Meta:
        model = Rider
        fields = [
            'full_name', 'display_name', 'dob', 'mobile_number', 'email',
            'profile_pic', 'aadhar_front', 'aadhar_back', 'pan_card_image',
            'driving_license_front', 'driving_license_back'
        ]
        extra_kwargs = {
            'email': {'required': False},
            'mobile_number': {'required': False},
        }

    def validate_email(self, value):
        """Check if email already exists for other riders"""
        if value:
            rider = self.instance
            if User.objects.filter(email=value).exclude(id=rider.user.id).exists():
                raise serializers.ValidationError("A user with this email already exists.")
        return value

    def validate_mobile_number(self, value):
        """Check if mobile number already exists for other riders"""
        if value:
            rider = self.instance
            if Rider.objects.filter(mobile_number=value).exclude(id=rider.id).exists():
                raise serializers.ValidationError("A rider with this mobile number already exists.")
        return value

    def update(self, instance, validated_data):
        """Update rider and user data"""
        # Update user email if provided
        if 'email' in validated_data:
            email = validated_data['email']
            if email and instance.user:
                instance.user.email = email
                instance.user.username = email  # Keep username synced with email
                instance.user.save()
        
        # Update rider fields
        return super().update(instance, validated_data)


class RiderPasswordChangeSerializer(serializers.Serializer):
    """Serializer for changing rider password"""
    old_password = serializers.CharField(write_only=True)
    new_password = serializers.CharField(write_only=True, min_length=8)
    confirm_password = serializers.CharField(write_only=True)

    def validate(self, attrs):
        if attrs['new_password'] != attrs['confirm_password']:
            raise serializers.ValidationError("New password and confirm password do not match.")
        return attrs

    def validate_old_password(self, value):
        """Check if old password is correct"""
        user = self.context['request'].user
        if not user.check_password(value):
            raise serializers.ValidationError("Old password is incorrect.")
        return value

    def save(self):
        """Update user password"""
        user = self.context['request'].user
        user.set_password(self.validated_data['new_password'])
        user.save()
        return user

class RiderSerializer(serializers.ModelSerializer):
    class Meta:
        model = Rider
        fields = ['id', 'full_name', 'mobile_number', 'profile_pic', 'status']
