from rest_framework import generics, status, permissions
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from rest_framework.views import APIView
from django.shortcuts import get_object_or_404
from django.db.models import Q
from django.utils import timezone

from course.serializers_exam import CertificateSearchSerializer

from .models import Batch, AllCourse, Certificate, Chapter, Lesson, CourseEnrollment, LessonProgress
from .serializers import (
    BatchSerializer, AllCourseSerializer, CourseDetailSerializer,
    ChapterSerializer, LessonSerializer, CourseEnrollmentSerializer,
    LessonProgressSerializer
)
from subscriptions.models import Profile

class BatchListView(generics.ListCreateAPIView):
    """List and create batches"""
    queryset = Batch.objects.filter(is_active=True)
    serializer_class = BatchSerializer
    #permission_classes = [permissions.IsAuthenticated]

class BatchDetailView(generics.RetrieveUpdateDestroyAPIView):
    """Retrieve, update, or delete a batch"""
    queryset = Batch.objects.all()
    serializer_class = BatchSerializer
    #permission_classes = [permissions.IsAuthenticated]

class CourseListView(generics.ListCreateAPIView):
    """List and create courses"""
    serializer_class = AllCourseSerializer
    #permission_classes = [permissions.IsAuthenticated]
    
    def get_queryset(self):
        queryset = AllCourse.objects.filter(is_published=True)
        
        # Filter by batch if provided
        batch_id = self.request.query_params.get('batch_id')
        if batch_id:
            queryset = queryset.filter(batch_id=batch_id)
        
        # Filter by trainer if provided
        trainer_id = self.request.query_params.get('trainer_id')
        if trainer_id:
            queryset = queryset.filter(trainer_id=trainer_id)
        
        return queryset

class CourseDetailView(generics.RetrieveUpdateDestroyAPIView):
    """Retrieve detailed course information with chapters and lessons"""
    queryset = AllCourse.objects.all()
    serializer_class = CourseDetailSerializer
    #permission_classes = [permissions.IsAuthenticated]

class ChapterListView(generics.ListCreateAPIView):
    """List and create chapters for a course"""
    serializer_class = ChapterSerializer
    #permission_classes = [permissions.IsAuthenticated]
    
    def get_queryset(self):
        course_id = self.kwargs.get('course_id')
        return Chapter.objects.filter(course_id=course_id, is_published=True)

class ChapterDetailView(generics.RetrieveUpdateDestroyAPIView):
    """Retrieve, update, or delete a chapter"""
    queryset = Chapter.objects.all()
    serializer_class = ChapterSerializer
    #permission_classes = [permissions.IsAuthenticated]

class LessonListView(generics.ListCreateAPIView):
    """List and create lessons for a chapter"""
    serializer_class = LessonSerializer
    #permission_classes = [permissions.IsAuthenticated]
    
    def get_queryset(self):
        chapter_id = self.kwargs.get('chapter_id')
        return Lesson.objects.filter(chapter_id=chapter_id, is_published=True)

class LessonDetailView(generics.RetrieveUpdateDestroyAPIView):
    """Retrieve, update, or delete a lesson"""
    queryset = Lesson.objects.all()
    serializer_class = LessonSerializer
    #permission_classes = [permissions.IsAuthenticated]

class CourseEnrollmentView(APIView):
    """Handle course enrollment and unenrollment"""
    #permission_classes = [permissions.IsAuthenticated]
    
    def post(self, request, course_id):
        """Enroll in a course"""
        try:
            course = get_object_or_404(AllCourse, id=course_id, is_published=True)
            profile = request.user.profile
            
            # Check if already enrolled
            enrollment, created = CourseEnrollment.objects.get_or_create(
                course=course,
                student=profile,
                defaults={'is_active': True}
            )
            
            if not created and enrollment.is_active:
                return Response(
                    {'message': 'Already enrolled in this course'},
                    status=status.HTTP_400_BAD_REQUEST
                )
            
            if not created:
                enrollment.is_active = True
                enrollment.is_deleted = False
                enrollment.save()
            
            serializer = CourseEnrollmentSerializer(enrollment)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
            
        except Exception as e:
            return Response(
                {'error': str(e)},
                status=status.HTTP_400_BAD_REQUEST
            )
    
    def delete(self, request, course_id):
        """Unenroll from a course"""
        try:
            course = get_object_or_404(AllCourse, id=course_id)
            profile = request.user.profile
            
            enrollment = get_object_or_404(
                CourseEnrollment,
                course=course,
                student=profile,
                is_active=True
            )
            
            enrollment.is_active = False
            enrollment.save()
            
            return Response(
                {'message': 'Successfully unenrolled from course'},
                status=status.HTTP_200_OK
            )
            
        except Exception as e:
            return Response(
                {'error': str(e)},
                status=status.HTTP_400_BAD_REQUEST
            )

class UserCoursesView(generics.ListAPIView):
    """Get all courses enrolled by the current user"""
    serializer_class = AllCourseSerializer
    #permission_classes = [permissions.IsAuthenticated]
    
    def get_queryset(self):
        profile = self.request.user.profile
        enrollments = CourseEnrollment.objects.filter(
            student=profile,
            is_active=True
        ).values_list('course', flat=True)
        
        return AllCourse.objects.filter(
            id__in=enrollments,
            is_published=True
        )

class LessonProgressView(APIView):
    """Handle lesson progress tracking"""
    #permission_classes = [permissions.IsAuthenticated]
    
    def post(self, request, lesson_id):
        """Update lesson progress"""
        try:
            lesson = get_object_or_404(Lesson, id=lesson_id)
            profile = request.user.profile
            
            # Get enrollment
            enrollment = get_object_or_404(
                CourseEnrollment,
                course=lesson.chapter.course,
                student=profile,
                is_active=True
            )
            
            # Get or create progress
            progress, created = LessonProgress.objects.get_or_create(
                enrollment=enrollment,
                lesson=lesson
            )
            
            # Update progress data
            time_watched = request.data.get('time_watched', progress.time_watched)
            last_position = request.data.get('last_position', progress.last_position)
            is_completed = request.data.get('is_completed', False)
            
            progress.time_watched = time_watched
            progress.last_position = last_position
            
            if is_completed and not progress.is_completed:
                progress.mark_completed()
            elif not is_completed and progress.is_completed:
                progress.is_completed = False
                progress.completed_at = None
            
            progress.save()
            
            serializer = LessonProgressSerializer(progress)
            return Response(serializer.data, status=status.HTTP_200_OK)
            
        except Exception as e:
            return Response(
                {'error': str(e)},
                status=status.HTTP_400_BAD_REQUEST
            )
    
    def get(self, request, lesson_id):
        """Get lesson progress"""
        try:
            lesson = get_object_or_404(Lesson, id=lesson_id)
            profile = request.user.profile
            
            enrollment = get_object_or_404(
                CourseEnrollment,
                course=lesson.chapter.course,
                student=profile,
                is_active=True
            )
            
            progress = get_object_or_404(
                LessonProgress,
                enrollment=enrollment,
                lesson=lesson
            )
            
            serializer = LessonProgressSerializer(progress)
            return Response(serializer.data, status=status.HTTP_200_OK)
            
        except Exception as e:
            return Response(
                {'error': str(e)},
                status=status.HTTP_400_BAD_REQUEST
            )

class CourseProgressView(APIView):
    """Get overall course progress for a user"""
    #permission_classes = [permissions.IsAuthenticated]
    
    def get(self, request, course_id):
        """Get course progress details"""
        try:
            course = get_object_or_404(AllCourse, id=course_id)
            profile = request.user.profile
            
            enrollment = get_object_or_404(
                CourseEnrollment,
                course=course,
                student=profile,
                is_active=True
            )
            
            # Get all lessons in the course
            lessons = Lesson.objects.filter(
                chapter__course=course,
                is_published=True
            ).order_by('chapter__order', 'order')
            
            # Get progress for each lesson
            progress_data = []
            completed_lessons = 0
            
            for lesson in lessons:
                try:
                    progress = LessonProgress.objects.get(
                        enrollment=enrollment,
                        lesson=lesson
                    )
                    lesson_data = {
                        'lesson_id': lesson.id,
                        'lesson_title': lesson.title,
                        'chapter_title': lesson.chapter.title,
                        'is_completed': progress.is_completed,
                        'time_watched': progress.time_watched,
                        'last_position': progress.last_position,
                        'completed_at': progress.completed_at
                    }
                    if progress.is_completed:
                        completed_lessons += 1
                except LessonProgress.DoesNotExist:
                    lesson_data = {
                        'lesson_id': lesson.id,
                        'lesson_title': lesson.title,
                        'chapter_title': lesson.chapter.title,
                        'is_completed': False,
                        'time_watched': 0,
                        'last_position': 0,
                        'completed_at': None
                    }
                
                progress_data.append(lesson_data)
            
            total_lessons = lessons.count()
            progress_percentage = round((completed_lessons / total_lessons * 100), 2) if total_lessons > 0 else 0
            
            return Response({
                'course_id': course.id,
                'course_name': course.name,
                'total_lessons': total_lessons,
                'completed_lessons': completed_lessons,
                'progress_percentage': progress_percentage,
                'lessons_progress': progress_data
            }, status=status.HTTP_200_OK)
            
        except Exception as e:
            return Response(
                {'error': str(e)},
                status=status.HTTP_400_BAD_REQUEST
            )

@api_view(['GET'])
@permission_classes([permissions.IsAuthenticated])
def search_courses(request):
    """Search courses by name, description, or trainer"""
    query = request.query_params.get('q', '')
    
    if not query:
        return Response(
            {'error': 'Query parameter "q" is required'},
            status=status.HTTP_400_BAD_REQUEST
        )
    
    courses = AllCourse.objects.filter(
        Q(name__icontains=query) |
        Q(description__icontains=query) |
        Q(trainer__name__icontains=query),
        is_published=True
    )
    
    serializer = AllCourseSerializer(courses, many=True, context={'request': request})
    return Response(serializer.data, status=status.HTTP_200_OK)


class CertificateListAllView(generics.ListAPIView):
    """List all certificates"""
    serializer_class = CertificateSearchSerializer
    #permission_classes = [permissions.IsAuthenticated]
    
    def get_queryset(self):
        return Certificate.objects.all()
    