from django.contrib import admin
from django.utils import timezone

from apps.mentorship.models import (
    ASSIGNMENT_ACTIVE,
    Mentor,
    MentorAssignment,
    MentorSession,
    SESSION_SCHEDULED,
)


class MentorSessionInline(admin.TabularInline):
    model = MentorSession
    extra = 0
    fields = ('scheduled_at', 'duration_minutes', 'meeting_link', 'status', 'notes')
    ordering = ['scheduled_at']


@admin.register(Mentor)
class MentorAdmin(admin.ModelAdmin):
    list_display = (
        'user', 'is_verified', 'is_active', 'max_active_students',
        'active_students', 'expertise_tags', 'created_at',
    )
    list_filter = ('is_verified', 'is_active', 'categories')
    search_fields = (
        'user__username', 'user__email', 'user__full_name',
        'bio', 'expertise_tags',
    )
    filter_horizontal = ('categories', 'courses')
    raw_id_fields = ('user',)

    @admin.display(description='Active mentees')
    def active_students(self, obj):
        return f'{obj.active_assignment_count()} / {obj.max_active_students}'


@admin.register(MentorAssignment)
class MentorAssignmentAdmin(admin.ModelAdmin):
    """Mentor dashboard core: assigned students + sessions inline."""
    list_display = (
        'student', 'mentor', 'course', 'status', 'weekly_cadence', 'assigned_at',
    )
    list_filter = ('status', 'weekly_cadence', 'course__category', 'course')
    search_fields = (
        'student__username', 'student__email', 'student__full_name',
        'mentor__user__username', 'mentor__user__full_name',
        'course__title',
    )
    raw_id_fields = ('mentor', 'student', 'course')
    inlines = [MentorSessionInline]


@admin.register(MentorSession)
class MentorSessionAdmin(admin.ModelAdmin):
    list_display = (
        'assignment', 'scheduled_at', 'duration_minutes', 'status', 'meeting_link',
    )
    list_filter = ('status', 'scheduled_at')
    search_fields = (
        'assignment__student__username',
        'assignment__mentor__user__username',
        'assignment__course__title',
        'notes', 'meeting_link',
    )
    raw_id_fields = ('assignment',)
    actions = ('mark_completed', 'mark_cancelled')

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        # Mentors with a profile only see their own sessions in admin when not superuser
        user = request.user
        if user.is_superuser or getattr(user, 'role', None) == 'admin':
            return qs
        if hasattr(user, 'mentor_profile'):
            return qs.filter(assignment__mentor=user.mentor_profile)
        return qs.none()

    @admin.action(description='Mark completed')
    def mark_completed(self, request, queryset):
        from apps.mentorship.models import SESSION_COMPLETED
        updated = queryset.update(status=SESSION_COMPLETED)
        self.message_user(request, f'Marked {updated} session(s) completed.')

    @admin.action(description='Cancel sessions')
    def mark_cancelled(self, request, queryset):
        from apps.mentorship.models import SESSION_CANCELLED
        updated = queryset.update(status=SESSION_CANCELLED)
        self.message_user(request, f'Cancelled {updated} session(s).')
