from rest_framework import viewsets
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import AllowAny, IsAuthenticatedOrReadOnly
from .models import (
    Category, Project, Coupon, Banner, Student, StudentCoupon,
    Activity, Showcase, Exam, StudentHonor, StudentLevel,
    CourseRegistration, ActivityRegistration, ExamRegistration
)
from .serializers import (
    CategorySerializer, ProjectSerializer, CouponSerializer, BannerSerializer, StudentSerializer, StudentCouponSerializer,
    ActivitySerializer, ShowcaseSerializer, ExamSerializer, StudentHonorSerializer, StudentLevelSerializer,
    CourseRegistrationSerializer, ActivityRegistrationSerializer, ExamRegistrationSerializer
)

class CategoryViewSet(viewsets.ModelViewSet):
    queryset = Category.objects.all()
    serializer_class = CategorySerializer
    permission_classes = [AllowAny]
    pagination_class = None  # Return all categories without pagination for the app
    search_fields = ['name']

class ProjectViewSet(viewsets.ModelViewSet):
    queryset = Project.objects.select_related('category').all()
    serializer_class = ProjectSerializer
    permission_classes = [IsAuthenticatedOrReadOnly]
    search_fields = ['title', 'category__name']
    filterset_fields = ['category']

class CouponViewSet(viewsets.ModelViewSet):
    queryset = Coupon.objects.all()
    serializer_class = CouponSerializer
    permission_classes = [IsAuthenticatedOrReadOnly]
    search_fields = ['title']
    filterset_fields = ['status']

class BannerViewSet(viewsets.ModelViewSet):
    queryset = Banner.objects.select_related('project').all().order_by('sort_order')
    serializer_class = BannerSerializer
    permission_classes = [IsAuthenticatedOrReadOnly]
    filterset_fields = ['is_active']

class StudentCouponViewSet(viewsets.ModelViewSet):
    queryset = StudentCoupon.objects.select_related('student', 'coupon').all()
    serializer_class = StudentCouponSerializer
    permission_classes = [IsAuthenticatedOrReadOnly]

class StudentViewSet(viewsets.ModelViewSet):
    queryset = Student.objects.all()
    serializer_class = StudentSerializer
    permission_classes = [IsAuthenticatedOrReadOnly]
    search_fields = ['name', 'phone']

    def perform_create(self, serializer):
        student = serializer.save()
        auto_coupons = Coupon.objects.filter(issue_type='registration')
        created = []
        for c in auto_coupons:
            sc = StudentCoupon.objects.create(student=student, coupon=c)
            created.append(sc)
        student.coupon_count = StudentCoupon.objects.filter(student=student).count()
        student.save(update_fields=['coupon_count'])

    @action(detail=True, methods=['post'])
    def assign_coupon(self, request, pk=None):
        student = self.get_object()
        coupon_id = request.data.get('coupon_id')
        try:
            coupon = Coupon.objects.get(pk=coupon_id)
        except Coupon.DoesNotExist:
            return Response({"detail": "优惠券不存在"}, status=status.HTTP_404_NOT_FOUND)
        sc = StudentCoupon.objects.create(student=student, coupon=coupon)
        student.coupon_count = StudentCoupon.objects.filter(student=student).count()
        student.save(update_fields=['coupon_count'])
        return Response(StudentCouponSerializer(sc).data, status=status.HTTP_201_CREATED)

class UserProfileView(APIView):
    """
    Mock View for Mini Program to get 'current' user.
    In a real app, this would get request.user.
    Here we return the first student or a mock.
    """
    permission_classes = [AllowAny]

    def get(self, request):
        student = Student.objects.first()
        if student:
            serializer = StudentSerializer(student)
            return Response(serializer.data)
        else:
            # Fallback if no student exists
            return Response({
                "id": "8839201",
                "name": "学员用户",
                "avatar": "https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?w=200&auto=format&fit=crop&q=60",
                "stats": {
                    "learning": 0,
                    "coupons": 0,
                    "hours": 0
                }
            })

    def post(self, request):
        # Handle profile update from Mini Program
        student = Student.objects.first()
        if student:
            serializer = StudentSerializer(student, data=request.data, partial=True)
            if serializer.is_valid():
                serializer.save()
                return Response(serializer.data)
            return Response(serializer.errors, status=400)
        return Response({"message": "No user found"}, status=404)

class UserCouponsView(APIView):
    permission_classes = [AllowAny]

    def get(self, request):
        student = Student.objects.first()
        if not student:
            return Response([])
        scs = StudentCoupon.objects.select_related('coupon').filter(student=student)
        serializer = StudentCouponSerializer(scs, many=True)
        return Response(serializer.data)

class ActivityViewSet(viewsets.ModelViewSet):
    queryset = Activity.objects.all().order_by('start_time')
    serializer_class = ActivitySerializer
    permission_classes = [AllowAny] # Allow public to view
    filterset_fields = ['status']
    search_fields = ['title']

class ShowcaseViewSet(viewsets.ModelViewSet):
    queryset = Showcase.objects.all().order_by('-created_at')
    serializer_class = ShowcaseSerializer
    permission_classes = [AllowAny]

class ExamViewSet(viewsets.ModelViewSet):
    queryset = Exam.objects.all().order_by('exam_date')
    serializer_class = ExamSerializer
    permission_classes = [AllowAny]

class StudentHonorViewSet(viewsets.ModelViewSet):
    queryset = StudentHonor.objects.select_related('student').all()
    serializer_class = StudentHonorSerializer
    permission_classes = [IsAuthenticatedOrReadOnly]
    filterset_fields = ['student']

class StudentLevelViewSet(viewsets.ModelViewSet):
    queryset = StudentLevel.objects.select_related('student', 'exam').all()
    serializer_class = StudentLevelSerializer
    permission_classes = [IsAuthenticatedOrReadOnly]
    filterset_fields = ['student']

class CourseRegistrationViewSet(viewsets.ModelViewSet):
    queryset = CourseRegistration.objects.select_related('student', 'project').all()
    serializer_class = CourseRegistrationSerializer
    permission_classes = [IsAuthenticatedOrReadOnly]
    filterset_fields = ['student', 'status']

class ActivityRegistrationViewSet(viewsets.ModelViewSet):
    queryset = ActivityRegistration.objects.select_related('student', 'activity').all()
    serializer_class = ActivityRegistrationSerializer
    permission_classes = [IsAuthenticatedOrReadOnly]
    filterset_fields = ['student', 'status']

class ExamRegistrationViewSet(viewsets.ModelViewSet):
    queryset = ExamRegistration.objects.select_related('student', 'exam').all()
    serializer_class = ExamRegistrationSerializer
    permission_classes = [IsAuthenticatedOrReadOnly]
    filterset_fields = ['student', 'status']
