from rest_framework import serializers
from .models import Category, Teacher, TeachingCenter, Project, Coupon, Banner, Student, StudentCoupon, StudentProject, StudentHonor, StudentShowcase, Notification, NotificationBatch

class AbsoluteURLField(serializers.CharField):
    def to_representation(self, value):
        if not value:
            return value
        if value.startswith(('http://', 'https://')):
            return value
        request = self.context.get('request')
        if request:
            return request.build_absolute_uri(value)
        return value

    def to_internal_value(self, data):
        if data and isinstance(data, str) and data.startswith(('http://', 'https://')):
            # If it's an absolute URL, try to extract the relative path
            # We assume standard media URL structure '/media/'
            if '/media/' in data:
                return '/media/' + data.split('/media/', 1)[1]
        return super().to_internal_value(data)

class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Category
        fields = '__all__'

class TeacherSerializer(serializers.ModelSerializer):
    class Meta:
        model = Teacher
        fields = '__all__'

class TeachingCenterSerializer(serializers.ModelSerializer):
    class Meta:
        model = TeachingCenter
        fields = '__all__'

class ProjectSerializer(serializers.ModelSerializer):
    # category_name = serializers.CharField(source='category.name', read_only=True)
    # category_color = serializers.CharField(source='category.color', read_only=True)
    category_name = serializers.CharField(source='get_project_type_display', read_only=True)
    category_color = serializers.SerializerMethodField()
    teacher_name = serializers.SerializerMethodField()
    project_type_display = serializers.CharField(source='get_project_type_display', read_only=True)
    image = AbsoluteURLField()

    class Meta:
        model = Project
        fields = '__all__'
    
    def get_category_color(self, obj):
        colors = {
            'training': 'bg-cyan-100 text-cyan-600',
            'competition': 'bg-purple-100 text-purple-600',
            'grading': 'bg-blue-100 text-blue-600'
        }
        return colors.get(obj.project_type, 'bg-gray-100 text-gray-600')

    def get_teacher_name(self, obj):
        if obj.teacher:
            return obj.teacher.name
        return obj.custom_teacher

class CouponSerializer(serializers.ModelSerializer):
    scope_text = serializers.SerializerMethodField()
    applicable_project_titles = serializers.SerializerMethodField()

    class Meta:
        model = Coupon
        fields = '__all__'

    def get_scope_text(self, obj):
        ids = list(obj.applicable_projects.values_list('id', flat=True))
        if not ids:
            return '通用'
        names = list(obj.applicable_projects.values_list('title', flat=True))
        return '，'.join(names)

    def get_applicable_project_titles(self, obj):
        return list(obj.applicable_projects.values_list('title', flat=True))

class StudentCouponSerializer(serializers.ModelSerializer):
    coupon_detail = CouponSerializer(source='coupon', read_only=True)
    student_name = serializers.CharField(source='student.name', read_only=True)
    student_phone = serializers.CharField(source='student.phone', read_only=True)
    coupon_title = serializers.CharField(source='coupon.title', read_only=True)
    status_display = serializers.CharField(source='get_status_display', read_only=True)

    class Meta:
        model = StudentCoupon
        fields = '__all__'

class BannerSerializer(serializers.ModelSerializer):
    project_title = serializers.CharField(source='project.title', read_only=True)
    image = AbsoluteURLField()
    class Meta:
        model = Banner
        fields = '__all__'

class StudentSerializer(serializers.ModelSerializer):
    teacher_name = serializers.CharField(source='responsible_teacher.name', read_only=True)
    teaching_center_name = serializers.CharField(source='teaching_center.name', read_only=True)
    stats = serializers.SerializerMethodField()
    enrolled_projects = serializers.SerializerMethodField()
    coupons = serializers.PrimaryKeyRelatedField(many=True, read_only=True, source='student_coupons')
    status_display = serializers.CharField(source='get_status_display', read_only=True)
    teacher = serializers.PrimaryKeyRelatedField(source='responsible_teacher', queryset=Teacher.objects.all(), required=False, allow_null=True)
    avatar = AbsoluteURLField()

    class Meta:
        model = Student
        fields = ['id', 'name', 'phone', 'age', 'city', 'address', 'avatar', 'wechat_nickname', 'openid', 'teacher', 'teacher_name', 'teaching_center', 'teaching_center_name', 'company_name', 'position', 'status', 'status_display', 'stats', 'enrolled_projects', 'coupons', 'created_at']
        read_only_fields = ['stats', 'enrolled_projects', 'coupons', 'teaching_center_name', 'teacher_name', 'status_display']

    def get_stats(self, obj):
        return {
            "learning": obj.learning_count,
            "coupons": obj.coupon_count,
            "hours": obj.study_hours
        }

    def get_enrolled_projects(self, obj):
        enrollments = obj.enrollments.all()
        data = []
        for enrollment in enrollments:
            data.append({
                "project_title": enrollment.project.title,
                "status": enrollment.status,
                "status_display": enrollment.get_status_display()
            })
        return data

class StudentProjectSerializer(serializers.ModelSerializer):
    student_name = serializers.CharField(source='student.name', read_only=True)
    student_phone = serializers.CharField(source='student.phone', read_only=True)
    project_title = serializers.CharField(source='project.title', read_only=True)
    project_image = AbsoluteURLField(source='project.image', read_only=True)
    project_type = serializers.CharField(source='project.project_type', read_only=True)
    project_type_display = serializers.CharField(source='project.get_project_type_display', read_only=True)

    class Meta:
        model = StudentProject
        fields = '__all__'

class StudentHonorSerializer(serializers.ModelSerializer):
    student_name = serializers.CharField(source='student.name', read_only=True)
    student_phone = serializers.CharField(source='student.phone', read_only=True)
    student_avatar = AbsoluteURLField(source='student.avatar', read_only=True)
    student_openid = serializers.CharField(source='student.openid', read_only=True)
    student_teaching_center = serializers.CharField(source='student.teacher.name', read_only=True)
    student_company_name = serializers.CharField(source='student.company_name', read_only=True)
    image = AbsoluteURLField()

    class Meta:
        model = StudentHonor
        fields = '__all__'

class StudentShowcaseSerializer(serializers.ModelSerializer):
    student_name = serializers.CharField(source='student.name', read_only=True)
    cover_image = AbsoluteURLField()
    video_url = AbsoluteURLField()

    class Meta:
        model = StudentShowcase
        fields = '__all__'

class NotificationSerializer(serializers.ModelSerializer):
    class Meta:
        model = Notification
        fields = '__all__'

class NotificationBatchSerializer(serializers.ModelSerializer):
    send_mode_display = serializers.CharField(source='get_send_mode_display', read_only=True)
    notification_type_display = serializers.CharField(source='get_notification_type_display', read_only=True)
    
    class Meta:
        model = NotificationBatch
        fields = '__all__'

