from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from .models import Course, Lesson, LessonEnrollment
from .forms import LessonForm, EnrollmentForm

def schedule_list(request):
    lessons = Lesson.objects.all().order_by('date', 'start_time')
    return render(request, 'schedule/schedule_list.html', {'lessons': lessons})

@login_required
def course_detail(request, pk):
    course = get_object_or_404(Course, pk=pk)
    lessons = Lesson.objects.filter(course=course).order_by('start_time')
    return render(request, 'schedule/course_detail.html', {
        'course': course,
        'lessons': lessons
    })

@login_required
def lesson_detail(request, pk):
    lesson = get_object_or_404(Lesson, pk=pk)
    return render(request, 'schedule/lesson_detail.html', {'lesson': lesson})

@login_required
def create_lesson(request):
    if not hasattr(request.user, 'instructor'):
        messages.error(request, 'У вас нет прав для создания занятий.')
        return redirect('schedule:list')
    
    if request.method == 'POST':
        form = LessonForm(request.POST)
        if form.is_valid():
            lesson = form.save(commit=False)
            lesson.instructor = request.user.instructor
            lesson.save()
            messages.success(request, 'Занятие успешно создано.')
            return redirect('schedule:list')
    else:
        form = LessonForm()
    
    return render(request, 'schedule/lesson_form.html', {'form': form, 'action': 'create'})

@login_required
def update_lesson(request, pk):
    lesson = get_object_or_404(Lesson, pk=pk)
    
    if not hasattr(request.user, 'instructor') or lesson.instructor != request.user.instructor:
        messages.error(request, 'У вас нет прав для редактирования этого занятия.')
        return redirect('schedule:list')
    
    if request.method == 'POST':
        form = LessonForm(request.POST, instance=lesson)
        if form.is_valid():
            form.save()
            messages.success(request, 'Занятие успешно обновлено.')
            return redirect('schedule:list')
    else:
        form = LessonForm(instance=lesson)
    
    return render(request, 'schedule/lesson_form.html', {'form': form, 'action': 'update'})

@login_required
def delete_lesson(request, pk):
    lesson = get_object_or_404(Lesson, pk=pk)
    
    if not hasattr(request.user, 'instructor') or lesson.instructor != request.user.instructor:
        messages.error(request, 'У вас нет прав для удаления этого занятия.')
        return redirect('schedule:list')
    
    if request.method == 'POST':
        lesson.delete()
        messages.success(request, 'Занятие успешно удалено.')
        return redirect('schedule:list')
    
    return render(request, 'schedule/lesson_confirm_delete.html', {'lesson': lesson})

@login_required
def enroll_lesson(request, pk):
    lesson = get_object_or_404(Lesson, pk=pk)
    
    if not hasattr(request.user, 'student'):
        messages.error(request, 'Только студенты могут записываться на занятия.')
        return redirect('schedule:list')
    
    if lesson.enrolled_students.count() >= lesson.max_students:
        messages.error(request, 'К сожалению, все места на это занятие уже заняты.')
        return redirect('schedule:list')
    
    if request.user.student in lesson.enrolled_students.all():
        messages.warning(request, 'Вы уже записаны на это занятие.')
    else:
        lesson.enrolled_students.add(request.user.student)
        messages.success(request, 'Вы успешно записались на занятие.')
    
    return redirect('schedule:detail', pk=pk)

@login_required
def enrollment_detail(request, pk):
    enrollment = get_object_or_404(LessonEnrollment, pk=pk)
    return render(request, 'schedule/enrollment_detail.html', {'enrollment': enrollment})

@login_required
def enrollment_create(request):
    if request.method == 'POST':
        form = EnrollmentForm(request.POST)
        if form.is_valid():
            enrollment = form.save()
            messages.success(request, 'Запись на занятие успешно создана!')
            return redirect('enrollment_detail', pk=enrollment.pk)
    else:
        form = EnrollmentForm()
    return render(request, 'schedule/enrollment_form.html', {'form': form}) 