from flask import Blueprint, render_template, redirect, url_for, flash, request, jsonify, send_file, Response
import csv
from io import StringIO, BytesIO
from datetime import datetime
from flask_login import login_required, current_user
from app import db
from app.models.user import User
from app.models.topic import Topic
from app.models.progress import Progress, Submission
from app.models.activity import Activity
from app.models.team import TeamMember
from app.services.email_service import send_approval_email, send_rejection_email
from app.forms.admin import TeacherForm, StudentForm, TeamMemberForm
from functools import wraps
from collections import defaultdict
from reportlab.lib import colors
from reportlab.lib.pagesizes import letter
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, HRFlowable
from reportlab.lib.units import inch
from werkzeug.utils import secure_filename
import os
from app.models.course import ShortCourse, LearningCourse
from app.forms.admin import ShortCourseForm, LearningCourseForm

admin_bp = Blueprint('admin', __name__)

def admin_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if not current_user.is_authenticated or current_user.role != 'admin':
            flash('Access denied.', 'error')
            return redirect(url_for('auth.login'))
        return f(*args, **kwargs)
    return decorated_function

@admin_bp.route('/dashboard')
@login_required
@admin_required
def dashboard():
    # Get current time for display
    now = datetime.utcnow
    
    # Get statistics for the dashboard
    stats = {
        'total_students': User.query.filter_by(role='student').count(),
        'total_teachers': User.query.filter_by(role='teacher').count(),
        'pending_approvals': User.query.filter_by(role='student', is_approved=False).count(),
        'total_topics': Topic.query.count()
    }
    
    # Get recent activities
    recent_activities = Activity.query.order_by(Activity.created_at.desc()).limit(10).all()
    
    return render_template('admin/dashboard.html', 
                         stats=stats,
                         recent_activities=recent_activities,
                         now=now)

@admin_bp.route('/topics')
@login_required
@admin_required
def topics():
    # Get all topics with additional data for the enhanced UI
    all_topics = Topic.query.all()
    
    # Group topics by category
    categories = defaultdict(list)
    for topic in all_topics:
        # Add additional properties needed for the UI
        topic.student_count = Progress.query.filter_by(topic_id=topic.id).distinct(Progress.student_id).count()
        topic.completion_count = Progress.query.filter_by(
            topic_id=topic.id, 
            comprehension_completed=True
        ).count()
        
        # Set publication status
        topic.is_published = True  # Assuming all topics are published by default
        
        # Add to category dictionary
        categories[topic.category].append(topic)
    
    return render_template('admin/topics.html', 
                         categories=dict(categories),
                         now=datetime.utcnow)  # Pass the now function to template

@admin_bp.route('/topics/<topic_id>')
@login_required
@admin_required
def get_topic(topic_id):
    topic = Topic.query.get_or_404(topic_id)
    
    # Enhance the topic data for the modal view
    topic_data = topic.to_dict()
    
    # Add teacher name
    if topic.teacher:
        topic_data['teacher_name'] = topic.teacher.username
    
    # Add statistics
    student_count = Progress.query.filter_by(topic_id=topic.id).distinct(Progress.student_id).count()
    completion_count = Progress.query.filter_by(topic_id=topic.id, comprehension_completed=True).count()
    
    topic_data['student_count'] = student_count
    topic_data['question_count'] = len(topic.comprehension_questions) if topic.comprehension_questions else 0
    
    # Calculate completion rate
    if student_count > 0:
        topic_data['completion_rate'] = f"{int(completion_count / student_count * 100)}%"
    else:
        topic_data['completion_rate'] = "0%"
    
    # Calculate average score
    scores = [p.comprehension_score for p in Progress.query.filter_by(topic_id=topic.id) 
             if p.comprehension_score is not None]
    
    if scores:
        topic_data['average_score'] = f"{int(sum(scores) / len(scores))}%"
    else:
        topic_data['average_score'] = "N/A"
    
    # Add questions list
    topic_data['questions'] = [{"id": q.id, "text": q.text} for q in topic.comprehension_questions]
    
    # Set publication status (you may want to actually store this in your database)
    topic_data['is_published'] = True  # Assuming all topics are published
    
    return jsonify(topic_data)

@admin_bp.route('/topics/<topic_id>/pdf')
@login_required
@admin_required
def download_topic_pdf(topic_id):
    topic = Topic.query.get_or_404(topic_id)
    
    # Create a BytesIO buffer to receive PDF data
    buffer = BytesIO()
    
    # Create the PDF document with improved styling
    doc = SimpleDocTemplate(
        buffer,
        pagesize=letter,
        rightMargin=72,
        leftMargin=72,
        topMargin=72,
        bottomMargin=72
    )
    
    # Get styles with enhancements
    styles = getSampleStyleSheet()
    
    # Create custom styles for a more professional look
    title_style = ParagraphStyle(
        'CustomTitle',
        parent=styles['Heading1'],
        fontSize=24,
        textColor=colors.darkblue,
        spaceAfter=16,
        spaceBefore=12,
        alignment=1  # Center alignment
    )
    
    heading_style = ParagraphStyle(
        'CustomHeading',
        parent=styles['Heading2'],
        fontSize=16,
        textColor=colors.darkblue,
        spaceBefore=12,
        spaceAfter=6,
        borderWidth=0,
        borderColor=colors.darkblue,
        borderPadding=(0, 0, 3, 0),
        borderRadius=None
    )
    
    normal_style = styles['Normal']
    normal_style.fontSize = 12
    normal_style.leading = 14
    
    # Create custom style for questions with better formatting
    question_style = ParagraphStyle(
        'QuestionStyle',
        parent=styles['Normal'],
        fontSize=12,
        leftIndent=20,
        spaceBefore=8,
        spaceAfter=8,
        bulletIndent=10,
        bulletText='•'
    )
    
    # Create a metadata style
    metadata_style = ParagraphStyle(
        'MetadataStyle',
        parent=styles['Normal'],
        fontSize=10,
        textColor=colors.grey,
        alignment=2  # Right alignment
    )
    
    # Create the story (content) for the PDF with improved structure
    story = []
    
    # Add document title with improved styling
    story.append(Paragraph(topic.title, title_style))
    
    # Add metadata (category, author, date)
    story.append(Paragraph(f"Category: {topic.category}", metadata_style))
    story.append(Paragraph(f"Created by: {topic.teacher.username}", metadata_style))
    story.append(Paragraph(f"Created on: {topic.created_at.strftime('%B %d, %Y')}", metadata_style))
    
    # Add divider
    story.append(Spacer(1, 24))
    story.append(HRFlowable(width="100%", thickness=1, color=colors.lightgrey, spaceAfter=10))
    story.append(Spacer(1, 12))
    
    # Add reading content section with better spacing and formatting
    story.append(Paragraph("Reading Content", heading_style))
    story.append(Spacer(1, 12))
    
    # Split the reading content into paragraphs for better formatting
    paragraphs = topic.reading_content.split('\n\n')
    for para in paragraphs:
        if para.strip():
            story.append(Paragraph(para.strip(), normal_style))
            story.append(Spacer(1, 6))
    
    story.append(Spacer(1, 12))
    
    # Add comprehension questions section with better formatting
    if topic.comprehension_questions:
        story.append(Paragraph("Comprehension Questions", heading_style))
        story.append(Spacer(1, 12))
        
        for i, question in enumerate(topic.comprehension_questions, 1):
            story.append(Paragraph(f"<strong>Q{i}:</strong> {question.text}", question_style))
        
        story.append(Spacer(1, 12))
    
    # Add writing prompt section with better styling
    if topic.writing_prompt:
        story.append(Paragraph("Writing Prompt", heading_style))
        story.append(Spacer(1, 12))
        story.append(Paragraph(topic.writing_prompt, normal_style))
        story.append(Spacer(1, 12))
    
    # Add speaking prompt section with better styling
    if topic.speaking_prompt:
        story.append(Paragraph("Speaking Prompt", heading_style))
        story.append(Spacer(1, 12))
        story.append(Paragraph(topic.speaking_prompt, normal_style))
    
    # Add speaking questions if available
    if hasattr(topic, 'speaking_questions') and topic.speaking_questions:
        story.append(Spacer(1, 12))
        story.append(Paragraph("Speaking Questions", heading_style))
        story.append(Spacer(1, 12))
        
        for i, question in enumerate(topic.speaking_questions, 1):
            story.append(Paragraph(f"<strong>Q{i}:</strong> {question.text}", question_style))
    
    # Add footer with page numbers
    def add_page_number(canvas, doc):
        canvas.saveState()
        canvas.setFont('Helvetica', 9)
        canvas.setFillColor(colors.grey)
        page_num = canvas.getPageNumber()
        text = f"Page {page_num}"
        canvas.drawRightString(letter[0] - 72, 36, text)
        canvas.restoreState()
    
    try:
        # Build the PDF with page numbers
        doc.build(story, onFirstPage=add_page_number, onLaterPages=add_page_number)
        
        # Reset buffer position to the beginning
        buffer.seek(0)
        
        return send_file(
            buffer,
            download_name=f"{topic.title.replace(' ', '_')}.pdf",
            mimetype='application/pdf',
            as_attachment=True
        )
    except Exception as e:
        flash(f'Error generating PDF: {str(e)}', 'error')
        return redirect(url_for('admin.topics'))

@admin_bp.route('/add-teacher', methods=['POST'])
@login_required
@admin_required
def add_teacher():
    form = TeacherForm(editing=False)  # Password is required for new teachers
    if form.validate():
        if User.query.filter_by(email=form.email.data).first():
            flash('Email already registered.', 'error')
            return redirect(url_for('admin.manage_teachers'))
        
        teacher = User(
            username=form.username.data,
            email=form.email.data,
            role='teacher',
            is_approved=True
        )
        teacher.set_password(form.password.data)
        db.session.add(teacher)
        db.session.commit()
        
        Activity.log(
            action=Activity.ACTIONS['TEACHER_ADDED'],
            user=current_user,
            target_user=teacher,
            details=f"Added new teacher account for {teacher.username}"
        )
        
        flash('Teacher added successfully!', 'success')
        return redirect(url_for('admin.manage_teachers'))
    
    for field, errors in form.errors.items():
        for error in errors:
            flash(f'{getattr(form, field).label.text}: {error}', 'error')
    
    return redirect(url_for('admin.manage_teachers'))

@admin_bp.route('/teachers/<teacher_id>', methods=['DELETE'])
@login_required
@admin_required
def delete_teacher(teacher_id):
    teacher = User.query.filter_by(id=teacher_id, role='teacher').first_or_404()
    
    # Check if teacher has any students or topics
    if teacher.students.count() > 0:
        return jsonify({
            'error': 'Cannot delete teacher with assigned students. Please reassign students first.'
        }), 400
    
    if Topic.query.filter_by(teacher_id=teacher.id).count() > 0:
        return jsonify({
            'error': 'Cannot delete teacher with existing topics. Please delete or reassign topics first.'
        }), 400
    
    Activity.log(
        action=Activity.ACTIONS['TEACHER_DELETED'],
        user=current_user,
        target_user=teacher,
        details=f"Deleted teacher account for {teacher.username}"
    )
    
    db.session.delete(teacher)
    db.session.commit()
    return jsonify({'message': 'Teacher deleted successfully'})

@admin_bp.route('/manage-teachers')
@login_required
@admin_required
def manage_teachers():
    teachers = User.query.filter_by(role='teacher').all()
    form = TeacherForm()
    return render_template('admin/manage_teachers.html', teachers=teachers, form=form)

@admin_bp.route('/manage-students')
@login_required
@admin_required
def manage_students():
    students = User.query.filter_by(role='student').all()
    form = StudentForm()
    # Get all teachers for the form's select field
    teachers = User.query.filter_by(role='teacher').all()
    form.teacher.choices = [(t.id, t.username) for t in teachers]
    return render_template('admin/manage_students.html', students=students, form=form)

@admin_bp.route('/add-student', methods=['POST'])
@login_required
@admin_required
def add_student():
    form = StudentForm()
    # Get all teachers for the form's select field
    teachers = User.query.filter_by(role='teacher').all()
    form.teacher.choices = [(t.id, t.username) for t in teachers]
    
    if form.validate_on_submit():
        if User.query.filter_by(email=form.email.data).first():
            flash('Email already registered.', 'error')
            return redirect(url_for('admin.manage_students'))
        
        student = User(
            username=form.username.data,
            email=form.email.data,
            role='student',
            is_approved=True,
            teacher_id=form.teacher.data,
            roll_number=form.roll_number.data,
            section=form.section.data,
            program=form.program.data,
            department=form.department.data
        )
        student.set_password(form.password.data)
        db.session.add(student)
        db.session.commit()
        
        Activity.log(
            action=Activity.ACTIONS['STUDENT_ADDED'],
            user=current_user,
            target_user=student,
            details=f"Added new student account for {student.username}"
        )
        
        flash('Student added successfully!', 'success')
        return redirect(url_for('admin.manage_students'))
    
    for field, errors in form.errors.items():
        for error in errors:
            flash(f'{getattr(form, field).label.text}: {error}', 'error')
    
    return redirect(url_for('admin.manage_students'))

@admin_bp.route('/approvals')
@login_required
@admin_required
def approvals():
    pending_requests = User.query.filter_by(role='student', is_approved=False).all()
    teachers = User.query.filter_by(role='teacher').all()
    return render_template('admin/approvals.html', 
                         approval_requests=pending_requests,
                         teachers=teachers,
                         pending_count=len(pending_requests))

@admin_bp.route('/assign_teacher/<user_id>', methods=['POST'])
@login_required
@admin_required
def assign_teacher(user_id):
    data = request.get_json()
    teacher_id = data.get('teacher_id')
    
    if not teacher_id:
        return jsonify({'error': 'Teacher ID is required'}), 400
    
    user = User.query.get_or_404(user_id)
    teacher = User.query.filter_by(id=teacher_id, role='teacher').first_or_404()
    
    user.teacher_id = teacher.id
    db.session.commit()
    
    Activity.log(
        action=Activity.ACTIONS['STUDENT_UPDATED'],
        user=current_user,
        target_user=user,
        details=f"Assigned student {user.username} to teacher {teacher.username}"
    )
    
    return jsonify({'message': 'Teacher assigned successfully'})

@admin_bp.route('/approve/<user_id>', methods=['POST'])
@login_required
@admin_required
def approve_user(user_id):
    user = User.query.get_or_404(user_id)
    
    if not user.teacher_id:
        return jsonify({'error': 'Cannot approve user without assigned teacher'}), 400
    
    user.is_approved = True
    db.session.commit()
    
    Activity.log(
        action=Activity.ACTIONS['USER_APPROVED'],
        user=current_user,
        target_user=user,
        details=f"Approved student {user.username}"
    )
    
    try:
        send_approval_email(user)
    except Exception as e:
        print(f"Failed to send approval email: {e}")
    
    return jsonify({'message': 'User approved successfully'})

@admin_bp.route('/reject/<user_id>', methods=['POST'])
@login_required
@admin_required
def reject_user(user_id):
    user = User.query.get_or_404(user_id)
    
    Activity.log(
        action=Activity.ACTIONS['USER_REJECTED'],
        user=current_user,
        target_user=user,
        details=f"Rejected student application for {user.username}"
    )
    
    try:
        send_rejection_email(user)
    except Exception as e:
        print(f"Failed to send rejection email: {e}")
    
    db.session.delete(user)
    db.session.commit()
    
    return jsonify({'message': 'User rejected successfully'})

@admin_bp.route('/students/<int:student_id>/edit', methods=['GET', 'POST'])
@login_required
@admin_required
def edit_student(student_id):
    student = User.query.filter_by(id=student_id, role='student').first_or_404()
    form = StudentForm(obj=student)
    teachers = User.query.filter_by(role='teacher').all()
    form.teacher.choices = [(t.id, t.username) for t in teachers]
    
    if request.method == 'POST' and form.validate_on_submit():
        student.username = form.username.data
        student.email = form.email.data
        student.roll_number = form.roll_number.data
        student.section = form.section.data
        student.program = form.program.data
        student.department = form.department.data
        student.teacher_id = form.teacher.data
        
        if form.password.data:
            student.set_password(form.password.data)
        
        db.session.commit()
        
        Activity.log(
            action=Activity.ACTIONS['STUDENT_UPDATED'],
            user=current_user,
            target_user=student,
            details=f"Updated student information for {student.username}"
        )
        
        flash('Student information updated successfully!', 'success')
        return redirect(url_for('admin.view_student', student_id=student.id))
    
    return render_template('admin/edit_student.html', form=form, student=student)

@admin_bp.route('/teachers/<int:teacher_id>/edit', methods=['GET', 'POST'])
@login_required
@admin_required
def edit_teacher(teacher_id):
    teacher = User.query.filter_by(id=teacher_id, role='teacher').first_or_404()
    form = TeacherForm(editing=True, obj=teacher)
    
    if request.method == 'POST' and form.validate_on_submit():
        teacher.username = form.username.data
        teacher.email = form.email.data
        
        # Only update password if provided
        if form.password.data:
            teacher.set_password(form.password.data)
        
        db.session.commit()
        
        Activity.log(
            action=Activity.ACTIONS['TEACHER_UPDATED'],
            user=current_user,
            target_user=teacher,
            details=f"Updated teacher information for {teacher.username}"
        )
        
        flash('Teacher information updated successfully!', 'success')
        return redirect(url_for('admin.manage_teachers'))
    
    return render_template('admin/edit_teacher.html', form=form, teacher=teacher)

@admin_bp.route('/students/<int:student_id>')
@login_required
@admin_required
def view_student(student_id):
    student = User.query.filter_by(id=student_id, role='student').first_or_404()
    return render_template('admin/view_student.html', student=student)

@admin_bp.route('/students/<int:student_id>', methods=['DELETE'])
@login_required
@admin_required
def delete_student(student_id):
    student = User.query.filter_by(id=student_id, role='student').first_or_404()
    
    # Check if student has any progress records
    if student.progress_records.count() > 0:
        return jsonify({
            'error': 'Cannot delete student with existing progress records. Please reset their progress first.'
        }), 400
    
    try:
        Activity.log(
            action=Activity.ACTIONS['STUDENT_DELETED'],
            user=current_user,
            target_user=student,
            details=f"Deleted student account for {student.username}"
        )
        
        db.session.delete(student)
        db.session.commit()
        return jsonify({'message': 'Student deleted successfully'})
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@admin_bp.route('/export-students')
@login_required
@admin_required
def export_students():
    try:
        students = User.query.filter_by(role='student').all()
        
        # Create a string buffer to write CSV data
        si = StringIO()
        writer = csv.writer(si)
        
        # Write headers
        writer.writerow(['ID', 'Username', 'Email', 'Roll Number', 'Section', 'Program', 
                        'Department', 'Teacher', 'Status', 'Created At'])
        
        # Write student data
        for student in students:
            writer.writerow([
                student.id,
                student.username,
                student.email,
                student.roll_number,
                student.section,
                student.program,
                student.department,
                student.teacher.username if student.teacher else 'Not Assigned',
                'Active' if student.is_approved else 'Pending',
                student.created_at.strftime('%Y-%m-%d %H:%M:%S')
            ])
        
        output = si.getvalue()
        si.close()
        
        return Response(
            output,
            mimetype='text/csv',
            headers={'Content-Disposition': 'attachment; filename=students.csv'}
        )
    except Exception as e:
        flash(f'Error exporting student data: {str(e)}', 'error')
        return redirect(url_for('admin.manage_students'))

@admin_bp.route('/add-short-course', methods=['GET', 'POST'])
@login_required
@admin_required
def add_short_course():
    form = ShortCourseForm()
    if form.validate_on_submit():
        course = ShortCourse(
            title=form.title.data,
            description=form.description.data
        )
        db.session.add(course)
        db.session.commit()
        flash('Short course added successfully!', 'success')
        return redirect(url_for('admin.add_short_course'))
    return render_template('admin/add_short_course.html', form=form)

@admin_bp.route('/add-learning-course', methods=['GET', 'POST'])
@login_required
@admin_required
def add_learning_course():
    form = LearningCourseForm()
    if form.validate_on_submit():
        course = LearningCourse(
            title=form.title.data,
            description=form.description.data
        )
        db.session.add(course)
        db.session.commit()
        flash('Learning course added successfully!', 'success')
        return redirect(url_for('admin.add_learning_course'))
    return render_template('admin/add_learning_course.html', form=form)

@admin_bp.route('/edit-short-course/<int:course_id>', methods=['GET', 'POST'])
@login_required
@admin_required
def edit_short_course(course_id):
    course = ShortCourse.query.get_or_404(course_id)
    form = ShortCourseForm(obj=course)
    if form.validate_on_submit():
        course.title = form.title.data
        course.description = form.description.data
        db.session.commit()
        flash('Short course updated successfully!', 'success')
        return redirect(url_for('admin.edit_short_course', course_id=course.id))
    return render_template('admin/edit_short_course.html', form=form, course=course)

@admin_bp.route('/delete-short-course/<int:course_id>', methods=['POST'])
@login_required
@admin_required
def delete_short_course(course_id):
    course = ShortCourse.query.get_or_404(course_id)
    db.session.delete(course)
    db.session.commit()
    flash('Short course deleted successfully!', 'success')
    return redirect(url_for('admin.dashboard'))

@admin_bp.route('/edit-learning-course/<int:course_id>', methods=['GET', 'POST'])
@login_required
@admin_required
def edit_learning_course(course_id):
    course = LearningCourse.query.get_or_404(course_id)
    form = LearningCourseForm(obj=course)
    if form.validate_on_submit():
        course.title = form.title.data
        course.description = form.description.data
        db.session.commit()
        flash('Learning course updated successfully!', 'success')
        return redirect(url_for('admin.edit_learning_course', course_id=course.id))
    return render_template('admin/edit_learning_course.html', form=form, course=course)

@admin_bp.route('/delete-learning-course/<int:course_id>', methods=['POST'])
@login_required
@admin_required
def delete_learning_course(course_id):
    course = LearningCourse.query.get_or_404(course_id)
    db.session.delete(course)
    db.session.commit()
    flash('Learning course deleted successfully!', 'success')
    return redirect(url_for('admin.dashboard'))

@admin_bp.route('/manage-courses')
@login_required
@admin_required
def manage_courses():
    short_courses = ShortCourse.query.all()
    learning_courses = LearningCourse.query.all()
    return render_template('admin/manage_courses.html', short_courses=short_courses, learning_courses=learning_courses)
# Team Management Routes
@admin_bp.route('/manage-team')
@login_required
@admin_required
def manage_team():
    academic_team = TeamMember.query.filter_by(team_type='academic', is_active=True).order_by(TeamMember.order).all()
    technical_team = TeamMember.query.filter_by(team_type='technical', is_active=True).order_by(TeamMember.order).all()
    admin_team = TeamMember.query.filter_by(team_type='administrative', is_active=True).order_by(TeamMember.order).all()
    
    return render_template('admin/manage_team.html', 
                         academic_team=academic_team,
                         technical_team=technical_team,
                         admin_team=admin_team)

@admin_bp.route('/add-team-member', methods=['GET', 'POST'])
@login_required
@admin_required
def add_team_member():
    form = TeamMemberForm()
    if form.validate_on_submit():
        # Check if member already exists
        existing = TeamMember.query.filter_by(name=form.name.data).first()
        if existing:
            flash('Team member with this name already exists.', 'error')
            return redirect(url_for('admin.manage_team'))
        
        profile_picture = None
        # Handle file upload
        if form.profile_picture.data:
            file = form.profile_picture.data
            if file:
                # Create upload directory if it doesn't exist
                upload_dir = os.path.join(os.path.dirname(__file__), '..', 'static', 'uploads', 'team_members')
                os.makedirs(upload_dir, exist_ok=True)
                
                # Generate unique filename
                import uuid
                ext = os.path.splitext(file.filename)[1]
                filename = f"{uuid.uuid4()}{ext}"
                filepath = os.path.join(upload_dir, filename)
                
                # Save file
                file.save(filepath)
                profile_picture = filename
        
        team_member = TeamMember(
            name=form.name.data,
            position=form.position.data,
            team_type=form.team_type.data,
            description=form.description.data,
            avatar_initials=form.avatar_initials.data,
            avatar_color=form.avatar_color.data,
            profile_picture=profile_picture,
            order=form.order.data if form.order.data else 0
        )
        db.session.add(team_member)
        db.session.commit()
        
        Activity.log(
            action=Activity.ACTIONS['TEACHER_ADDED'],
            user=current_user,
            target_user=None,
            details=f"Added team member: {team_member.name} ({team_member.position})"
        )
        
        flash('Team member added successfully!', 'success')
        return redirect(url_for('admin.manage_team'))
    
    return render_template('admin/add_team_member.html', form=form)

@admin_bp.route('/edit-team-member/<int:member_id>', methods=['GET', 'POST'])
@login_required
@admin_required
def edit_team_member(member_id):
    member = TeamMember.query.get_or_404(member_id)
    form = TeamMemberForm(obj=member)
    
    if form.validate_on_submit():
        member.name = form.name.data
        member.position = form.position.data
        member.team_type = form.team_type.data
        member.description = form.description.data
        member.avatar_initials = form.avatar_initials.data
        member.avatar_color = form.avatar_color.data
        if form.order.data is not None:
            member.order = form.order.data
        
        # Handle file upload
        if form.profile_picture.data:
            file = form.profile_picture.data
            if file:
                # Delete old profile picture if exists
                if member.profile_picture:
                    old_file_path = os.path.join(os.path.dirname(__file__), '..', 'static', 'uploads', 'team_members', member.profile_picture)
                    if os.path.exists(old_file_path):
                        os.remove(old_file_path)
                
                # Create upload directory if it doesn't exist
                upload_dir = os.path.join(os.path.dirname(__file__), '..', 'static', 'uploads', 'team_members')
                os.makedirs(upload_dir, exist_ok=True)
                
                # Generate unique filename
                import uuid
                ext = os.path.splitext(file.filename)[1]
                filename = f"{uuid.uuid4()}{ext}"
                filepath = os.path.join(upload_dir, filename)
                
                # Save file
                file.save(filepath)
                member.profile_picture = filename
        
        db.session.commit()
        
        Activity.log(
            action=Activity.ACTIONS['TEACHER_UPDATED'],
            user=current_user,
            target_user=None,
            details=f"Updated team member: {member.name}"
        )
        
        flash('Team member updated successfully!', 'success')
        return redirect(url_for('admin.manage_team'))
    
    return render_template('admin/edit_team_member.html', form=form, member=member)

@admin_bp.route('/delete-team-member/<int:member_id>', methods=['POST'])
@login_required
@admin_required
def delete_team_member(member_id):
    member = TeamMember.query.get_or_404(member_id)
    member_name = member.name
    
    db.session.delete(member)
    db.session.commit()
    
    Activity.log(
        action=Activity.ACTIONS['TEACHER_DELETED'],
        user=current_user,
        target_user=None,
        details=f"Deleted team member: {member_name}"
    )
    
    flash('Team member deleted successfully!', 'success')
    return redirect(url_for('admin.manage_team'))

@admin_bp.route('/reorder-team', methods=['POST'])
@login_required
@admin_required
def reorder_team():
    data = request.get_json()
    try:
        for item in data.get('items', []):
            member = TeamMember.query.get(item['id'])
            if member:
                member.order = item['order']
        db.session.commit()
        return jsonify({'success': True, 'message': 'Team order updated'})
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': str(e)}), 400