from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileAllowed
from wtforms import StringField, TextAreaField, IntegerField, SubmitField, PasswordField, SelectField
from wtforms.validators import DataRequired, Email, Length, NumberRange, Optional
from wtforms.fields import EmailField
from app.models.course import ShortCourse, LearningCourse

class AddStudentForm(FlaskForm):
    """Form for adding new students"""
    student_name = StringField('Student Name', validators=[
        DataRequired(),
        Length(min=3, max=50, message="Student name must be between 3 and 50 characters")
    ])
    email = EmailField('Email', validators=[
        DataRequired(),
        Email(message="Please enter a valid email address")
    ])
    password = PasswordField('Password', validators=[
        DataRequired(),
        Length(min=6, message="Password must be at least 6 characters long")
    ])
    roll_number = StringField('Roll Number', validators=[
        DataRequired(),
        Length(min=1, max=20, message="Roll number must be between 1 and 20 characters")
    ])
    department = StringField('Department', validators=[
        DataRequired(),
        Length(min=2, max=50, message="Department must be between 2 and 50 characters")
    ])
    program = StringField('Program', validators=[
        DataRequired(),
        Length(min=2, max=50, message="Program must be between 2 and 50 characters")
    ])
    semester = IntegerField('Semester', validators=[
        DataRequired(),
        NumberRange(min=1, max=12, message="Semester must be between 1 and 12")
    ])
    section = StringField('Section', validators=[
        DataRequired(),
        Length(min=1, max=10, message="Section must be between 1 and 10 characters")
    ])
    phone_number = StringField('Phone Number', validators=[
        DataRequired(),
        Length(min=10, max=15, message="Please enter a valid phone number")
    ])
    submit = SubmitField('Add Student')

class TopicForm(FlaskForm):
    """Form for creating and editing topics"""
    title = StringField('Title', validators=[DataRequired()])
    category = SelectField('Category', validators=[DataRequired()], choices=[
        ('general', 'General English'),
        ('business', 'Business English'),
        ('academic', 'Academic English'),
        ('conversation', 'Conversation Skills'),
        ('grammar', 'Grammar Essentials'),
        ('vocabulary', 'Vocabulary Building'),
        ('writing', 'Writing Skills'),
        ('reading', 'Reading Comprehension'),
        ('speaking', 'Speaking Practice'),
        ('listening', 'Listening Skills')
    ])
    reading_content = TextAreaField('Reading Content')
    image = FileField('Topic Image', validators=[FileAllowed(['jpg', 'jpeg', 'png', 'gif', 'webp'], 'Images only!')])
    speaking_prompt = TextAreaField('Speaking Prompt')
    writing_prompt = TextAreaField('Writing Prompt')
    course = SelectField('Course', validators=[DataRequired(message="Please select a course")], coerce=int)
    submit = SubmitField('Save Topic')

    def __init__(self, *args, **kwargs):
        super(TopicForm, self).__init__(*args, **kwargs)
        # Dynamically populate course choices
        self.course.choices = []
        try:
            # Get all courses for the current teacher
            from flask_login import current_user
            if current_user and current_user.is_authenticated:
                print(f"DEBUG - TopicForm.__init__: Loading courses for teacher ID {current_user.id}")
                
                # First try to get teacher-specific courses
                short_courses = ShortCourse.query.filter_by(teacher_id=current_user.id).all()
                learning_courses = LearningCourse.query.filter_by(teacher_id=current_user.id).all()
                
                print(f"DEBUG - Found {len(short_courses)} teacher short courses, {len(learning_courses)} teacher learning courses")
                
                # If no courses are found with the teacher's ID, get all courses
                if not short_courses and not learning_courses:
                    short_courses = ShortCourse.query.all()
                    learning_courses = LearningCourse.query.all()
                    print(f"DEBUG - Using all courses: {len(short_courses)} short courses, {len(learning_courses)} learning courses")
                
                # Combine both types of courses with type indicators
                self.course.choices = [
                    (course.id, f"Short Course: {course.title}") 
                    for course in short_courses
                ] + [
                    (course.id, f"Learning Course: {course.title}")
                    for course in learning_courses
                ]
                
                print(f"DEBUG - Set course.choices with {len(self.course.choices)} options")
                
                # Add a default option if there are no choices
                if not self.course.choices:
                    print("WARNING - No course choices available! Adding a placeholder.")
                    # Add a dummy choice to prevent validation errors
                    self.course.choices = [(0, "-- No Courses Available --")]
        except Exception as e:
            # Log the error but continue with empty choices
            print(f"ERROR - Error loading course choices: {str(e)}")
            self.course.choices = [(0, "-- Error Loading Courses --")]

class CourseOutlineForm(FlaskForm):
    """
    A form for adding or editing course outlines. Note that the sections and topics
    are handled dynamically in the template and processed in the route handler.
    The CSRF token from this form is used to protect the submission.
    """
    pass  # All fields are handled dynamically in the template

class ReviewSubmissionForm(FlaskForm):
    """Form for reviewing student submissions"""
    feedback = TextAreaField('Feedback')
    status = SelectField('Status', choices=[
        ('approved', 'Approved'),
        ('rejected', 'Rejected'),
        ('pending', 'Pending Review')
    ], validators=[DataRequired()])
    submit = SubmitField('Submit Review')