from flask import Blueprint, render_template, flash, redirect, url_for, request, abort
from flask_login import login_user, logout_user, login_required, current_user
from app.forms import LoginForm, ReplyForm, ContentForm, SubjectForm
from app.models import Admin, ContactMessage, SiteContent, Subject
from app.email_service import send_reply_to_contact
from app import db, login_manager
from datetime import datetime

admin = Blueprint('admin', __name__)

@login_manager.user_loader
def load_user(user_id):
    return Admin.query.get(int(user_id))

@admin.route('/login', methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
        return redirect(url_for('admin.dashboard'))

    form = LoginForm()
    if form.validate_on_submit():
        user = Admin.query.filter_by(username=form.username.data).first()
        if user and user.check_password(form.password.data):
            login_user(user, remember=form.remember_me.data)
            next_page = request.args.get('next')
            flash(f'Welcome back, {user.username}!', 'success')
            return redirect(next_page) if next_page else redirect(url_for('admin.dashboard'))
        else:
            flash('Invalid username or password', 'danger')

    return render_template('admin/login.html', form=form)

@admin.route('/logout')
@login_required
def logout():
    logout_user()
    flash('You have been logged out successfully.', 'info')
    return redirect(url_for('main.index'))

@admin.route('/dashboard')
@login_required
def dashboard():
    total_messages = ContactMessage.query.count()
    unread_messages = ContactMessage.query.filter_by(is_read=False).count()
    unreplied_messages = ContactMessage.query.filter_by(is_replied=False).count()
    total_subjects = Subject.query.count()
    active_subjects = Subject.query.filter_by(is_active=True).count()
    recent_messages = ContactMessage.query.order_by(ContactMessage.created_at.desc()).limit(5).all()

    return render_template('admin/dashboard.html',
                         total_messages=total_messages,
                         unread_messages=unread_messages,
                         unreplied_messages=unreplied_messages,
                         total_subjects=total_subjects,
                         active_subjects=active_subjects,
                         recent_messages=recent_messages)

@admin.route('/messages')
@login_required
def messages():
    page = request.args.get('page', 1, type=int)
    status = request.args.get('status', 'all')

    query = ContactMessage.query

    if status == 'unread':
        query = query.filter_by(is_read=False)
    elif status == 'unreplied':
        query = query.filter_by(is_replied=False)
    elif status == 'replied':
        query = query.filter_by(is_replied=True)

    messages = query.order_by(ContactMessage.created_at.desc()).paginate(
        page=page, per_page=10, error_out=False
    )

    return render_template('admin/messages.html', messages=messages, status=status)

@admin.route('/messages/<int:message_id>')
@login_required
def view_message(message_id):
    message = ContactMessage.query.get_or_404(message_id)
    if not message.is_read:
        message.is_read = True
        db.session.commit()
    return render_template('admin/view_message.html', message=message)

@admin.route('/messages/<int:message_id>/reply', methods=['GET', 'POST'])
@login_required
def reply_message(message_id):
    message = ContactMessage.query.get_or_404(message_id)
    form = ReplyForm()

    if form.validate_on_submit():
        message.reply_message = form.reply_message.data
        message.is_replied = True
        message.replied_at = datetime.utcnow()
        message.replied_by = current_user.id
        db.session.commit()

        email_sent = send_reply_to_contact(message, current_user)

        if email_sent:
            flash('Reply sent successfully!', 'success')
        else:
            flash('Reply saved but email could not be sent.', 'warning')
        return redirect(url_for('admin.messages'))

    return render_template('admin/reply.html', form=form, message=message)

@admin.route('/messages/<int:message_id>/delete', methods=['POST'])
@login_required
def delete_message(message_id):
    message = ContactMessage.query.get_or_404(message_id)
    db.session.delete(message)
    db.session.commit()
    flash('Message deleted successfully.', 'success')
    return redirect(url_for('admin.messages'))

@admin.route('/content')
@login_required
def content():
    contents = SiteContent.query.order_by(SiteContent.section, SiteContent.key).all()
    return render_template('admin/content.html', contents=contents)

@admin.route('/content/add', methods=['GET', 'POST'])
@login_required
def add_content():
    form = ContentForm()
    if form.validate_on_submit():
        existing = SiteContent.query.filter_by(
            section=form.section.data, key=form.key.data
        ).first()
        if existing:
            flash('Content already exists.', 'warning')
            return render_template('admin/content_form.html', form=form, title='Add Content')

        content = SiteContent(
            section=form.section.data,
            key=form.key.data,
            value=form.value.data,
            content_type=form.content_type.data,
            updated_by=current_user.id
        )
        db.session.add(content)
        db.session.commit()
        flash('Content added successfully!', 'success')
        return redirect(url_for('admin.content'))
    return render_template('admin/content_form.html', form=form, title='Add Content')

@admin.route('/content/<int:content_id>/edit', methods=['GET', 'POST'])
@login_required
def edit_content(content_id):
    content = SiteContent.query.get_or_404(content_id)
    form = ContentForm(obj=content)
    if form.validate_on_submit():
        content.section = form.section.data
        content.key = form.key.data
        content.value = form.value.data
        content.content_type = form.content_type.data
        content.updated_by = current_user.id
        db.session.commit()
        flash('Content updated successfully!', 'success')
        return redirect(url_for('admin.content'))
    return render_template('admin/content_form.html', form=form, title='Edit Content')

@admin.route('/content/<int:content_id>/delete', methods=['POST'])
@login_required
def delete_content(content_id):
    content = SiteContent.query.get_or_404(content_id)
    db.session.delete(content)
    db.session.commit()
    flash('Content deleted successfully.', 'success')
    return redirect(url_for('admin.content'))

@admin.route('/subjects')
@login_required
def admin_subjects():
    subjects = Subject.query.order_by(Subject.display_order, Subject.name).all()
    return render_template('admin/subjects.html', subjects=subjects)

@admin.route('/subjects/add', methods=['GET', 'POST'])
@login_required
def add_subject():
    form = SubjectForm()
    if form.validate_on_submit():
        existing = Subject.query.filter_by(code=form.code.data).first()
        if existing:
            flash('Subject code already exists.', 'warning')
            return render_template('admin/subject_form.html', form=form, title='Add Subject')

        subject = Subject(
            name=form.name.data,
            code=form.code.data,
            grade_level=form.grade_level.data,
            description=form.description.data,
            icon=form.icon.data,
            color=form.color.data,
            display_order=int(form.display_order.data or 0),
            is_active=form.is_active.data
        )
        db.session.add(subject)
        db.session.commit()
        flash('Subject added successfully!', 'success')
        return redirect(url_for('admin.admin_subjects'))
    return render_template('admin/subject_form.html', form=form, title='Add Subject')

@admin.route('/subjects/<int:subject_id>/edit', methods=['GET', 'POST'])
@login_required
def edit_subject(subject_id):
    subject = Subject.query.get_or_404(subject_id)
    form = SubjectForm(obj=subject)
    if form.validate_on_submit():
        existing = Subject.query.filter(Subject.code == form.code.data, Subject.id != subject_id).first()
        if existing:
            flash('Subject code already exists.', 'warning')
            return render_template('admin/subject_form.html', form=form, title='Edit Subject')

        subject.name = form.name.data
        subject.code = form.code.data
        subject.grade_level = form.grade_level.data
        subject.description = form.description.data
        subject.icon = form.icon.data
        subject.color = form.color.data
        subject.display_order = int(form.display_order.data or 0)
        subject.is_active = form.is_active.data
        db.session.commit()
        flash('Subject updated successfully!', 'success')
        return redirect(url_for('admin.admin_subjects'))
    return render_template('admin/subject_form.html', form=form, title='Edit Subject')

@admin.route('/subjects/<int:subject_id>/toggle', methods=['POST'])
@login_required
def toggle_subject(subject_id):
    subject = Subject.query.get_or_404(subject_id)
    subject.is_active = not subject.is_active
    db.session.commit()
    flash(f'Subject updated successfully.', 'success')
    return redirect(url_for('admin.admin_subjects'))

@admin.route('/subjects/<int:subject_id>/delete', methods=['POST'])
@login_required
def delete_subject(subject_id):
    subject = Subject.query.get_or_404(subject_id)
    db.session.delete(subject)
    db.session.commit()
    flash('Subject deleted successfully.', 'success')
    return redirect(url_for('admin.admin_subjects'))
