from flask import Blueprint, render_template, flash, redirect, url_for, request, current_app
from app.forms import ContactForm
from app.models import ContactMessage, Subject, SiteContent
from app.email_service import send_contact_notification
from app import db
from sqlalchemy import or_

main = Blueprint('main', __name__)

def get_content_value(section, key, default=''):
    """Helper function to get site content"""
    content = SiteContent.query.filter_by(section=section, key=key).first()
    return content.value if content else default

@main.route('/')
def index():
    subjects = Subject.query.filter_by(is_active=True).order_by(Subject.display_order).all()

    # Group subjects by grade level
    grade_10 = [s for s in subjects if s.grade_level == '10']
    grade_11 = [s for s in subjects if s.grade_level == '11']
    grade_12 = [s for s in subjects if s.grade_level == '12']
    rewrite = [s for s in subjects if s.grade_level == 'rewrite']

    return render_template('index.html',
                         grade_10=grade_10,
                         grade_11=grade_11,
                         grade_12=grade_12,
                         rewrite=rewrite,
                         content=get_content_value)

@main.route('/about')
def about():
    return render_template('about.html', content=get_content_value)

@main.route('/subjects')
def subjects():
    all_subjects = Subject.query.filter_by(is_active=True).order_by(Subject.display_order).all()
    grade_filter = request.args.get('grade', 'all')

    if grade_filter != 'all':
        filtered_subjects = [s for s in all_subjects if s.grade_level == grade_filter]
    else:
        filtered_subjects = all_subjects

    return render_template('subjects.html', 
                         subjects=filtered_subjects, 
                         grade_filter=grade_filter,
                         content=get_content_value)

# @main.route('/contact', methods=['GET', 'POST'])
# def contact():
#     form = ContactForm()

#     if form.validate_on_submit():
#         message = ContactMessage(
#             name=form.name.data,
#             email=form.email.data,
#             phone=form.phone.data,
#             subject=form.subject.data,
#             message=form.message.data
#         )

#         db.session.add(message)
#         db.session.commit()

#         # Send email notification
#         email_sent = send_contact_notification(message)

#         if email_sent:
#             flash('Thank you for your message! We will get back to you soon.', 'success')
#         else:
#             flash('Message saved but there was an issue sending the notification email. We will still receive your message.', 'warning')

#         return redirect(url_for('main.success'))

#     return render_template('contact.html', form=form, content=get_content_value)

# routes.py (or main/views.py)
from flask import render_template, request, flash, redirect, url_for, current_app
from flask_wtf import FlaskForm
from wtforms import StringField, TextAreaField, SubmitField
from wtforms.validators import DataRequired, Email
from app import mail  # or use smtplib directly
from flask_mail import Message
import smtplib
from email.mime.text import MIMEText

# Define the form class (if not already defined)
class ContactForm(FlaskForm):
    name = StringField('Your Name', validators=[DataRequired()])
    email = StringField('Email Address', validators=[DataRequired(), Email()])
    phone = StringField('Phone Number (optional)')
    subject = StringField('Subject', validators=[DataRequired()])
    message = TextAreaField('Your Message', validators=[DataRequired()])
    submit = SubmitField('Send Message')

@main.route('/contact', methods=['GET', 'POST'])
def contact():
    form = ContactForm()  # CREATE THE FORM INSTANCE
    
    if form.validate_on_submit():  # Checks both POST and validation
        name = form.name.data
        email = form.email.data
        phone = form.phone.data
        subject = form.subject.data
        message = form.message.data
        
        try:
            # Use working smtplib method
            server = smtplib.SMTP('smtp.gmail.com', 587)
            server.starttls()
            server.login(
                current_app.config['MAIL_USERNAME'],
                current_app.config['MAIL_PASSWORD']
            )
            
            msg = MIMEText(f"""
New contact form submission:

Name: {name}
Email: {email}
Phone: {phone}
Subject: {subject}

Message:
{message}
            """)
            
            msg['Subject'] = f"Contact Form: {name}"
            msg['From'] = current_app.config['MAIL_USERNAME']
            msg['To'] = current_app.config['MAIL_USERNAME']
            msg['Reply-To'] = email
            
            server.send_message(msg)
            server.quit()
            
            flash('Your message has been sent successfully!', 'success')
            return redirect(url_for('main.success'))
            
        except Exception as e:
            import traceback
            print(f"ERROR: {e}")
            print(traceback.format_exc())
            flash(f'Failed to send message: {str(e)}', 'danger')
    
    # PASS FORM TO TEMPLATE (this was missing!)
    return render_template('contact.html', form=form)

@main.route('/success')
def success():
    return render_template('success.html')

@main.route('/subject/<int:subject_id>')
def subject_detail(subject_id):
    subject = Subject.query.get_or_404(subject_id)
    return render_template('subject_detail.html', subject=subject)

@main.route('/search')
def search():
    query = request.args.get('q', '')
    if query:
        subjects = Subject.query.filter(
            or_(
                Subject.name.ilike(f'%{query}%'),
                Subject.description.ilike(f'%{query}%')
            )
        ).filter_by(is_active=True).all()
    else:
        subjects = []

    return render_template('search_results.html', subjects=subjects, query=query)
