from flask import Blueprint, render_template, redirect, url_for, flash, request
from flask_login import login_user, logout_user, login_required, current_user
from app import db
from app.models.user import User
from app.forms.auth import LoginForm, SignupForm
from app.services.email_service import send_approval_notification, send_welcome_signup_email
from datetime import datetime
from app.models.course import ShortCourse, LearningCourse

auth_bp = Blueprint('auth', __name__)

@auth_bp.route('/login', methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
        return redirect(url_for(f'{current_user.role}.dashboard'))
    
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user and user.check_password(form.password.data):
            if not user.is_approved and user.role == 'student':
                flash('Your account is pending approval.', 'warning')
                return redirect(url_for('auth.approval_pending'))
            login_user(user)
            
            # Update last login time and streak
            user.last_login = datetime.utcnow()
            if user.role == 'student':
                user.update_login_streak()
            db.session.commit()
            
            next_page = request.args.get('next')
            return redirect(next_page or url_for(f'{user.role}.dashboard'))
        flash('Invalid email or password.', 'error')
    return render_template('auth/login.html', form=form)

@auth_bp.route('/signup', methods=['GET', 'POST'])
def signup():
    if current_user.is_authenticated:
        return redirect(url_for(f'{current_user.role}.dashboard'))

    course_id = request.args.get('course_id')
    form = SignupForm()
    # Gather all courses
    short_courses = ShortCourse.query.all()
    learning_courses = LearningCourse.query.all()

    # Flat list required for WTForms 2.x SelectField.pre_validate compatibility.
    # Grouped tuples like ('Short Courses', [...]) cause pre_validate to fail
    # because WTForms 2.x treats the group label as the choice value.
    form.enrolling_course.choices = (
        [('', 'Select a course (optional)')]
        + [(f'short_{c.id}', c.title) for c in short_courses]
        + [(f'learn_{c.id}', c.title) for c in learning_courses]
    )

    if course_id:
        form.enrolling_course.data = course_id

    ctx = dict(form=form, short_courses=short_courses, learning_courses=learning_courses)

    if form.validate_on_submit():
        # Check if email or username already exists
        if User.query.filter_by(email=form.email.data).first():
            flash('Email already registered.', 'error')
            return render_template('auth/signup.html', **ctx)

        if User.query.filter_by(username=form.username.data).first():
            flash('Username already taken.', 'error')
            return render_template('auth/signup.html', **ctx)

        user = User(
            username=form.username.data,
            email=form.email.data,
            role='student',
            is_approved=False,
            roll_number=form.roll_number.data,
            section=form.section.data,
            program=form.program.data,
            department=form.department.data
        )
        user.set_password(form.password.data)
        db.session.add(user)
        db.session.commit()

        try:
            send_approval_notification(user)
            send_welcome_signup_email(user)
        except Exception as e:
            print(f"Failed to send notification email: {e}")

        flash('Registration successful! Please wait for approval.', 'success')
        return redirect(url_for('auth.approval_pending'))

    return render_template('auth/signup.html', **ctx)

@auth_bp.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('auth.login'))

@auth_bp.route('/forgot-password')
def forgot_password():
    return render_template('auth/forgot_password.html')

@auth_bp.route('/approval-pending')
def approval_pending():
    return render_template('auth/approval_pending.html')
