from flask import render_template, redirect, url_for, flash, request, jsonify, current_app
from flask_login import login_required, current_user
from app.models.social_share import SocialNetwork, create_default_social_networks
from app.extensions import db
from . import admin_bp

@admin_bp.route('/social-networks')
@login_required
def manage_social_networks():
    """Vista para administrar redes sociales"""
    social_networks = SocialNetwork.query.order_by(SocialNetwork.position).all()
    
    # Si no hay redes sociales, crear las predeterminadas
    if not social_networks:
        create_default_social_networks()
        social_networks = SocialNetwork.query.order_by(SocialNetwork.position).all()
        flash('Se han creado las redes sociales predeterminadas', 'success')
    
    return render_template(
        'admin/social/manage_networks.html',
        title='Gestionar Redes Sociales',
        social_networks=social_networks
    )

@admin_bp.route('/social-networks/create', methods=['GET', 'POST'])
@login_required
def create_social_network():
    """Vista para crear una nueva red social"""
    if request.method == 'POST':
        try:
            # Calcular la última posición disponible
            last_position = db.session.query(db.func.max(SocialNetwork.position)).scalar() or 0
            
            network = SocialNetwork(
                name=request.form['name'],
                icon=request.form['icon'],
                color=request.form['color'],
                url_pattern=request.form['url_pattern'],
                is_active=True if request.form.get('is_active') else False,
                requires_mobile=True if request.form.get('requires_mobile') else False,
                position=last_position + 1
            )
            
            db.session.add(network)
            db.session.commit()
            
            flash(f'Red social {network.name} creada correctamente', 'success')
            return redirect(url_for('admin.manage_social_networks'))
        
        except Exception as e:
            flash(f'Error al crear red social: {str(e)}', 'error')
            db.session.rollback()
    
    return render_template(
        'admin/social/edit_network.html',
        title='Nueva Red Social',
        network=None
    )

@admin_bp.route('/social-networks/edit/<int:network_id>', methods=['GET', 'POST'])
@login_required
def edit_social_network(network_id):
    """Vista para editar una red social"""
    network = SocialNetwork.query.get_or_404(network_id)
    
    if request.method == 'POST':
        try:
            network.name = request.form['name']
            network.icon = request.form['icon']
            network.color = request.form['color']
            network.url_pattern = request.form['url_pattern']
            network.is_active = True if request.form.get('is_active') else False
            network.requires_mobile = True if request.form.get('requires_mobile') else False
            
            db.session.commit()
            
            flash(f'Red social {network.name} actualizada correctamente', 'success')
            return redirect(url_for('admin.manage_social_networks'))
        
        except Exception as e:
            flash(f'Error al actualizar red social: {str(e)}', 'error')
            db.session.rollback()
    
    return render_template(
        'admin/social/edit_network.html',
        title=f'Editar {network.name}',
        network=network
    )

@admin_bp.route('/social-networks/toggle/<int:network_id>', methods=['POST'])
@login_required
def toggle_social_network(network_id):
    """Activar/desactivar una red social"""
    network = SocialNetwork.query.get_or_404(network_id)
    
    try:
        network.is_active = not network.is_active
        db.session.commit()
        return jsonify({
            'success': True,
            'is_active': network.is_active,
            'message': f'{network.name} {"activada" if network.is_active else "desactivada"}'
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': str(e)}), 500

@admin_bp.route('/social-networks/delete/<int:network_id>', methods=['POST'])
@login_required
def delete_social_network(network_id):
    """Eliminar una red social"""
    network = SocialNetwork.query.get_or_404(network_id)
    
    try:
        name = network.name
        db.session.delete(network)
        db.session.commit()
        flash(f'Red social {name} eliminada correctamente', 'success')
    except Exception as e:
        db.session.rollback()
        flash(f'Error al eliminar red social: {str(e)}', 'error')
    
    return redirect(url_for('admin.manage_social_networks'))

@admin_bp.route('/social-networks/reorder', methods=['POST'])
@login_required
def reorder_networks():
    """Reordenar las redes sociales"""
    try:
        positions = request.json.get('positions', {})
        
        for network_id, position in positions.items():
            network = SocialNetwork.query.get(int(network_id))
            if network:
                network.position = position
        
        db.session.commit()
        return jsonify({'success': True})
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': str(e)}), 500
