from flask import Blueprint, render_template, request, jsonify, flash, redirect, url_for
from flask_login import login_required, current_user
#from extensions import db
from app.extensions import db
from app.models.teacher import Teacher
from app.models.booking import Booking
from app.models.course import Course
from app.models.feedback import Feedback
from datetime import datetime, timedelta

teacher_bp = Blueprint('teacher', __name__)

@teacher_bp.before_request
@login_required
def require_teacher():
    """要求教师权限"""
    if not current_user.is_teacher:
        flash('您没有权限访问此页面。', 'error')
        return redirect(url_for('main.index'))

@teacher_bp.route('/')
def dashboard():
    """教师仪表盘"""
    teacher = Teacher.query.filter_by(user_id=current_user.id).first_or_404()
    
    # 统计数据
    stats = {
        'total_bookings': Booking.query.filter_by(teacher_id=teacher.id).count(),
        'completed_classes': Booking.query.filter_by(
            teacher_id=teacher.id, 
            status='completed'
        ).count(),
        'upcoming_classes': Booking.query.filter(
            Booking.teacher_id == teacher.id,
            Booking.status.in_(['confirmed', 'pending']),
            Booking.booking_time > datetime.utcnow()
        ).count(),
        'total_earnings': db.session.query(db.func.sum(Booking.total_amount)).filter(
            Booking.teacher_id == teacher.id,
            Booking.status == 'completed'
        ).scalar() or 0
    }
    
    # 即将开始的课程
    upcoming_bookings = Booking.query.filter(
        Booking.teacher_id == teacher.id,
        Booking.status.in_(['confirmed', 'pending']),
        Booking.booking_time > datetime.utcnow()
    ).order_by(Booking.booking_time.asc()).limit(5).all()
    
    # 最近的评价
    recent_feedbacks = Feedback.query.filter_by(
        teacher_id=teacher.id
    ).order_by(Feedback.created_at.desc()).limit(5).all()
    
    return render_template('teacher/dashboard.html',
                         teacher=teacher,
                         stats=stats,
                         upcoming_bookings=upcoming_bookings,
                         recent_feedbacks=recent_feedbacks)

@teacher_bp.route('/profile', methods=['GET', 'POST'])
def profile():
    """教师个人资料"""
    teacher = Teacher.query.filter_by(user_id=current_user.id).first_or_404()
    
    if request.method == 'POST':
        teacher.full_name = request.form.get('full_name')
        teacher.nationality = request.form.get('nationality')
        teacher.bio = request.form.get('bio')
        teacher.teaching_style = request.form.get('teaching_style')
        teacher.experience = request.form.get('experience', type=int)
        teacher.education = request.form.get('education')
        teacher.certification = request.form.get('certification')
        teacher.specialty = request.form.get('specialty')
        teacher.hourly_rate = request.form.get('hourly_rate', type=float)
        teacher.available_online = bool(request.form.get('available_online'))
        teacher.available_offline = bool(request.form.get('available_offline'))
        teacher.offline_locations = request.form.get('offline_locations')
        
        # 处理文件上传（简化版）
        if 'avatar' in request.files:
            avatar_file = request.files['avatar']
            if avatar_file and avatar_file.filename:
                # 这里应该实现文件保存逻辑
                filename = f"teacher_{teacher.id}_avatar.jpg"
                # avatar_file.save(os.path.join(app.config['UPLOAD_FOLDER'], 'avatars', filename))
                teacher.avatar = filename
        
        db.session.commit()
        flash('个人资料更新成功！', 'success')
        return redirect(url_for('teacher.profile'))
    
    return render_template('teacher/profile.html', teacher=teacher)

@teacher_bp.route('/bookings')
def bookings():
    """我的预约管理"""
    teacher = Teacher.query.filter_by(user_id=current_user.id).first_or_404()
    page = request.args.get('page', 1, type=int)
    per_page = 10
    status = request.args.get('status')
    
    query = Booking.query.filter_by(teacher_id=teacher.id)
    
    if status:
        query = query.filter_by(status=status)
    
    bookings = query.order_by(Booking.booking_time.desc()).paginate(
        page=page, per_page=per_page, error_out=False
    )
    
    return render_template('teacher/bookings.html', bookings=bookings)

@teacher_bp.route('/booking/<int:booking_id>')
def booking_detail(booking_id):
    """预约详情"""
    booking = Booking.query.get_or_404(booking_id)
    
    # 检查权限
    if booking.teacher.user_id != current_user.id:
        flash('您没有权限查看此预约。', 'error')
        return redirect(url_for('teacher.bookings'))
    
    return render_template('teacher/booking_detail.html', booking=booking)

@teacher_bp.route('/booking/<int:booking_id>/confirm', methods=['POST'])
def confirm_booking(booking_id):
    """确认预约"""
    booking = Booking.query.get_or_404(booking_id)
    
    # 检查权限
    if booking.teacher.user_id != current_user.id:
        flash('您没有权限操作此预约。', 'error')
        return redirect(url_for('teacher.bookings'))
    
    if booking.status != 'pending':
        flash('该预约无法确认。', 'error')
        return redirect(url_for('teacher.booking_detail', booking_id=booking_id))
    
    booking.status = 'confirmed'
    
    # 如果是线上课程，生成会议链接
    if booking.lesson_type == 'online':
        booking.meeting_link = f"https://meet.linguotree.com/class-{booking.id}"
    
    db.session.commit()
    
    flash('预约已确认。', 'success')
    return redirect(url_for('teacher.booking_detail', booking_id=booking_id))

@teacher_bp.route('/booking/<int:booking_id>/reject', methods=['POST'])
def reject_booking(booking_id):
    """拒绝预约"""
    booking = Booking.query.get_or_404(booking_id)
    
    # 检查权限
    if booking.teacher.user_id != current_user.id:
        flash('您没有权限操作此预约。', 'error')
        return redirect(url_for('teacher.bookings'))
    
    if booking.status != 'pending':
        flash('该预约无法拒绝。', 'error')
        return redirect(url_for('teacher.booking_detail', booking_id=booking_id))
    
    booking.status = 'cancelled'
    db.session.commit()
    
    flash('预约已拒绝。', 'success')
    return redirect(url_for('teacher.booking_detail', booking_id=booking_id))

@teacher_bp.route('/booking/<int:booking_id>/complete', methods=['POST'])
def complete_booking(booking_id):
    """标记课程完成"""
    booking = Booking.query.get_or_404(booking_id)
    
    # 检查权限
    if booking.teacher.user_id != current_user.id:
        flash('您没有权限操作此预约。', 'error')
        return redirect(url_for('teacher.bookings'))
    
    if booking.status != 'confirmed':
        flash('只有已确认的课程可以标记完成。', 'error')
        return redirect(url_for('teacher.booking_detail', booking_id=booking_id))
    
    booking.status = 'completed'
    db.session.commit()
    
    flash('课程已标记为完成。', 'success')
    return redirect(url_for('teacher.booking_detail', booking_id=booking_id))

@teacher_bp.route('/courses')
def courses():
    """我的课程管理"""
    teacher = Teacher.query.filter_by(user_id=current_user.id).first_or_404()
    courses = Course.query.filter_by(teacher_id=teacher.id).order_by(Course.created_at.desc()).all()
    
    return render_template('teacher/courses.html', courses=courses)

@teacher_bp.route('/course/create', methods=['GET', 'POST'])
def create_course():
    """创建课程"""
    teacher = Teacher.query.filter_by(user_id=current_user.id).first_or_404()
    
    if request.method == 'POST':
        title = request.form.get('title')
        description = request.form.get('description')
        course_type = request.form.get('course_type')
        level = request.form.get('level')
        category = request.form.get('category')
        duration = request.form.get('duration', type=int, default=60)
        price = request.form.get('price', type=float)
        max_students = request.form.get('max_students', type=int, default=1)
        curriculum = request.form.get('curriculum')
        
        if not all([title, course_type, level, price]):
            flash('请填写所有必填字段。', 'error')
            return render_template('teacher/create_course.html')
        
        course = Course(
            teacher_id=teacher.id,
            title=title,
            description=description,
            course_type=course_type,
            level=level,
            category=category,
            duration=duration,
            price=price,
            max_students=max_students,
            curriculum=curriculum,
            is_available=True
        )
        
        db.session.add(course)
        db.session.commit()
        
        flash('课程创建成功！', 'success')
        return redirect(url_for('teacher.courses'))
    
    return render_template('teacher/create_course.html')

@teacher_bp.route('/course/<int:course_id>/edit', methods=['GET', 'POST'])
def edit_course(course_id):
    """编辑课程"""
    course = Course.query.get_or_404(course_id)
    
    # 检查权限
    if course.teacher.user_id != current_user.id:
        flash('您没有权限编辑此课程。', 'error')
        return redirect(url_for('teacher.courses'))
    
    if request.method == 'POST':
        course.title = request.form.get('title')
        course.description = request.form.get('description')
        course.course_type = request.form.get('course_type')
        course.level = request.form.get('level')
        course.category = request.form.get('category')
        course.duration = request.form.get('duration', type=int, default=60)
        course.price = request.form.get('price', type=float)
        course.max_students = request.form.get('max_students', type=int, default=1)
        course.curriculum = request.form.get('curriculum')
        course.is_available = bool(request.form.get('is_available'))
        
        db.session.commit()
        flash('课程更新成功！', 'success')
        return redirect(url_for('teacher.courses'))
    
    return render_template('teacher/edit_course.html', course=course)

@teacher_bp.route('/schedule')
def schedule():
    """课程表"""
    teacher = Teacher.query.filter_by(user_id=current_user.id).first_or_404()
    
    # 获取未来30天的预约
    start_date = datetime.utcnow()
    end_date = start_date + timedelta(days=30)
    
    bookings = Booking.query.filter(
        Booking.teacher_id == teacher.id,
        Booking.booking_time >= start_date,
        Booking.booking_time <= end_date,
        Booking.status.in_(['confirmed', 'pending'])
    ).order_by(Booking.booking_time.asc()).all()
    
    return render_template('teacher/schedule.html', bookings=bookings)

@teacher_bp.route('/feedback')
def feedback():
    """学生评价"""
    teacher = Teacher.query.filter_by(user_id=current_user.id).first_or_404()
    
    feedbacks = Feedback.query.filter_by(
        teacher_id=teacher.id,
        is_public=True
    ).order_by(Feedback.created_at.desc()).all()
    
    return render_template('teacher/feedback.html', feedbacks=feedbacks)

@teacher_bp.route('/availability', methods=['GET', 'POST'])
def availability():
    """设置可用时间"""
    teacher = Teacher.query.filter_by(user_id=current_user.id).first_or_404()
    
    if request.method == 'POST':
        # 这里应该实现更复杂的时间段设置
        # 简化版：只更新基本可用性设置
        teacher.available_online = bool(request.form.get('available_online'))
        teacher.available_offline = bool(request.form.get('available_offline'))
        teacher.offline_locations = request.form.get('offline_locations')
        
        db.session.commit()
        flash('可用性设置已更新。', 'success')
        return redirect(url_for('teacher.availability'))
    
    return render_template('teacher/availability.html', teacher=teacher)