from flask import render_template, redirect, url_for, request, flash
from app import db
from app.models.faq import FAQ
from . import admin_bp
from app.blueprints.admin.routes import admin_required
from flask_login import login_required
from flask_wtf import FlaskForm
from wtforms import StringField, TextAreaField, IntegerField, BooleanField, SubmitField
from wtforms.validators import DataRequired, Length

class FAQForm(FlaskForm):
    """Formulario para crear y editar FAQs."""
    question = StringField('Pregunta', validators=[DataRequired(), Length(min=3, max=200)])
    answer = TextAreaField('Respuesta', validators=[DataRequired()])
    order = IntegerField('Orden', default=0)
    is_active = BooleanField('Activa', default=True)
    submit = SubmitField('Guardar')

@admin_bp.route('/faqs')
@login_required
@admin_required
def manage_faqs():
    """Lista todas las preguntas frecuentes."""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int) # Default to 10 items per page
        faqs_pagination = FAQ.query.order_by(FAQ.order).paginate(page=page, per_page=per_page, error_out=False)
        faqs = faqs_pagination.items
        return render_template('admin/faq/list.html', faqs=faqs, pagination=faqs_pagination, page=page, per_page=per_page)
    except Exception as e:
        flash(f'Error al cargar las preguntas frecuentes: {str(e)}', 'danger')
        return render_template('admin/faq/list.html', faqs=[])

@admin_bp.route('/faqs/new', methods=['GET', 'POST'])
@login_required
@admin_required
def create_faq():
    """Crea una nueva pregunta frecuente."""
    form = FAQForm()
    
    if form.validate_on_submit():
        try:
            faq = FAQ(
                question=form.question.data,
                answer=form.answer.data,
                order=form.order.data,
                is_active=form.is_active.data
            )
            db.session.add(faq)
            db.session.commit()
            flash('Pregunta frecuente creada con éxito.', 'success')
            return redirect(url_for('admin.manage_faqs'))
        except Exception as e:
            db.session.rollback()
            flash(f'Error al crear la pregunta frecuente: {str(e)}', 'danger')
    
    return render_template('admin/faq/form.html', form=form, title='Nueva pregunta frecuente')

@admin_bp.route('/faqs/edit/<int:faq_id>', methods=['GET', 'POST'])
@login_required
@admin_required
def edit_faq(faq_id):
    """Edita una pregunta frecuente existente."""
    faq = FAQ.query.get_or_404(faq_id)
    form = FAQForm(obj=faq)
    
    if form.validate_on_submit():
        try:
            form.populate_obj(faq)
            db.session.commit()
            flash('Pregunta frecuente actualizada con éxito.', 'success')
            return redirect(url_for('admin.manage_faqs'))
        except Exception as e:
            db.session.rollback()
            flash(f'Error al actualizar la pregunta frecuente: {str(e)}', 'danger')
    
    return render_template('admin/faq/form.html', form=form, title='Editar pregunta frecuente')

@admin_bp.route('/faqs/delete/<int:faq_id>', methods=['POST'])
@login_required
@admin_required
def delete_faq(faq_id):
    """Elimina una pregunta frecuente."""
    faq = FAQ.query.get_or_404(faq_id)
    try:
        db.session.delete(faq)
        db.session.commit()
        flash('Pregunta frecuente eliminada con éxito.', 'success')
    except Exception as e:
        db.session.rollback()
        flash(f'Error al eliminar la pregunta frecuente: {str(e)}', 'danger')
    
    return redirect(url_for('admin.manage_faqs'))
