from flask import render_template, redirect, url_for, flash, request
from app.superadmin import superadmin_bp
from app.auth.decorators import role_required
from app.models.school import School
from app.models.user import User
from app.extensions import db
from sqlalchemy import or_


@superadmin_bp.route('/')
@role_required('superadmin')
def dashboard():
    total_schools = School.query.count()
    pending_schools = School.query.filter_by(status='pending').count()
    approved_schools = School.query.filter_by(status='approved').count()
    total_users = User.query.filter(User.role != 'superadmin').count()
    total_guru = User.query.filter_by(role='guru').count()
    total_murid = User.query.filter_by(role='murid').count()
    recent_schools = School.query.order_by(School.created_at.desc()).limit(5).all()
    return render_template('superadmin/dashboard.html',
                           total_schools=total_schools,
                           pending_schools=pending_schools,
                           approved_schools=approved_schools,
                           total_users=total_users,
                           total_guru=total_guru,
                           total_murid=total_murid,
                           recent_schools=recent_schools)


# ==================== SCHOOL MANAGEMENT ====================

@superadmin_bp.route('/schools')
@role_required('superadmin')
def schools():
    status_filter = request.args.get('status', 'all')
    search = request.args.get('search', '').strip()
    page = request.args.get('page', 1, type=int)
    per_page = 10

    query = School.query

    # Apply status filter
    if status_filter != 'all':
        query = query.filter_by(status=status_filter)

    # Apply search filter
    if search:
        query = query.filter(
            or_(
                School.name.ilike(f'%{search}%'),
                School.npsn.ilike(f'%{search}%'),
                School.email.ilike(f'%{search}%')
            )
        )

    query = query.order_by(School.created_at.desc())
    pagination = query.paginate(page=page, per_page=per_page, error_out=False)

    return render_template('superadmin/schools.html',
                           pagination=pagination,
                           status_filter=status_filter,
                           search=search)


@superadmin_bp.route('/schools/<int:school_id>')
@role_required('superadmin')
def school_detail(school_id):
    school = School.query.get_or_404(school_id)
    admin = User.query.filter_by(school_id=school.id, role='admin').first()
    guru_count = User.query.filter_by(school_id=school.id, role='guru').count()
    murid_count = User.query.filter_by(school_id=school.id, role='murid').count()
    return render_template('superadmin/school_detail.html', school=school, admin=admin,
                           guru_count=guru_count, murid_count=murid_count)


@superadmin_bp.route('/schools/<int:school_id>/edit', methods=['GET', 'POST'])
@role_required('superadmin')
def edit_school(school_id):
    school = School.query.get_or_404(school_id)

    if request.method == 'POST':
        school.name = request.form.get('name', '').strip()
        school.npsn = request.form.get('npsn', '').strip()
        school.address = request.form.get('address', '').strip()
        school.phone = request.form.get('phone', '').strip()
        school.email = request.form.get('email', '').strip()

        if not school.name or not school.npsn:
            flash('Nama dan NPSN wajib diisi.', 'danger')
            return render_template('superadmin/edit_school.html', school=school)

        # Check NPSN uniqueness
        existing = School.query.filter(School.npsn == school.npsn, School.id != school.id).first()
        if existing:
            flash('NPSN sudah digunakan oleh sekolah lain.', 'danger')
            return render_template('superadmin/edit_school.html', school=school)

        db.session.commit()
        flash(f'Data sekolah "{school.name}" berhasil diperbarui.', 'success')
        return redirect(url_for('superadmin.school_detail', school_id=school.id))

    return render_template('superadmin/edit_school.html', school=school)


@superadmin_bp.route('/schools/<int:school_id>/delete', methods=['POST'])
@role_required('superadmin')
def delete_school(school_id):
    school = School.query.get_or_404(school_id)

    # Check if school has users
    user_count = User.query.filter_by(school_id=school.id).count()
    if user_count > 0:
        flash(f'Tidak dapat menghapus sekolah yang memiliki {user_count} pengguna. Hapus atau pindahkan semua pengguna terlebih dahulu.', 'danger')
        return redirect(url_for('superadmin.school_detail', school_id=school.id))

    school_name = school.name
    db.session.delete(school)
    db.session.commit()
    flash(f'Sekolah "{school_name}" berhasil dihapus.', 'success')
    return redirect(url_for('superadmin.schools'))


@superadmin_bp.route('/schools/bulk-action', methods=['POST'])
@role_required('superadmin')
def bulk_school_action():
    action = request.form.get('action')
    school_ids = request.form.getlist('school_ids')

    if not school_ids:
        flash('Tidak ada sekolah yang dipilih.', 'warning')
        return redirect(url_for('superadmin.schools'))

    if action == 'approve':
        for school_id in school_ids:
            school = School.query.get(school_id)
            if school and school.status == 'pending':
                school.status = 'approved'
                school.rejection_reason = None
        db.session.commit()
        flash(f'{len(school_ids)} sekolah berhasil disetujui.', 'success')
    elif action == 'reject':
        reason = request.form.get('reason', '')
        for school_id in school_ids:
            school = School.query.get(school_id)
            if school and school.status == 'pending':
                school.status = 'rejected'
                school.rejection_reason = reason
        db.session.commit()
        flash(f'{len(school_ids)} sekolah berhasil ditolak.', 'warning')
    elif action == 'suspend':
        for school_id in school_ids:
            school = School.query.get(school_id)
            if school and school.status == 'approved':
                school.status = 'suspended'
        db.session.commit()
        flash(f'{len(school_ids)} sekolah berhasil ditangguhkan.', 'warning')
    elif action == 'activate':
        for school_id in school_ids:
            school = School.query.get(school_id)
            if school and school.status in ['rejected', 'suspended']:
                school.status = 'approved'
                school.rejection_reason = None
        db.session.commit()
        flash(f'{len(school_ids)} sekolah berhasil diaktifkan.', 'success')

    return redirect(url_for('superadmin.schools'))


@superadmin_bp.route('/schools/<int:school_id>/approve', methods=['POST'])
@role_required('superadmin')
def approve_school(school_id):
    school = School.query.get_or_404(school_id)
    school.status = 'approved'
    school.rejection_reason = None
    db.session.commit()
    flash(f'Sekolah "{school.name}" telah disetujui. Alhamdulillah!', 'success')
    return redirect(url_for('superadmin.schools'))


@superadmin_bp.route('/schools/<int:school_id>/reject', methods=['POST'])
@role_required('superadmin')
def reject_school(school_id):
    school = School.query.get_or_404(school_id)
    school.status = 'rejected'
    school.rejection_reason = request.form.get('reason', '')
    db.session.commit()
    flash(f'Sekolah "{school.name}" telah ditolak.', 'warning')
    return redirect(url_for('superadmin.schools'))


@superadmin_bp.route('/schools/<int:school_id>/suspend', methods=['POST'])
@role_required('superadmin')
def suspend_school(school_id):
    school = School.query.get_or_404(school_id)
    school.status = 'suspended'
    db.session.commit()
    flash(f'Sekolah "{school.name}" telah ditangguhkan.', 'warning')
    return redirect(url_for('superadmin.schools'))


@superadmin_bp.route('/schools/<int:school_id>/activate', methods=['POST'])
@role_required('superadmin')
def activate_school(school_id):
    school = School.query.get_or_404(school_id)
    school.status = 'approved'
    school.rejection_reason = None
    db.session.commit()
    flash(f'Sekolah "{school.name}" telah diaktifkan kembali.', 'success')
    return redirect(url_for('superadmin.schools'))


# ==================== USER MANAGEMENT ====================

@superadmin_bp.route('/users')
@role_required('superadmin')
def users():
    role_filter = request.args.get('role', 'all')
    school_filter = request.args.get('school', 0, type=int)
    search = request.args.get('search', '').strip()
    page = request.args.get('page', 1, type=int)
    per_page = 15

    query = User.query.filter(User.role != 'superadmin')

    # Apply role filter
    if role_filter != 'all':
        query = query.filter_by(role=role_filter)

    # Apply school filter
    if school_filter:
        query = query.filter_by(school_id=school_filter)

    # Apply search filter
    if search:
        query = query.filter(
            or_(
                User.name.ilike(f'%{search}%'),
                User.email.ilike(f'%{search}%')
            )
        )

    query = query.order_by(User.created_at.desc())
    pagination = query.paginate(page=page, per_page=per_page, error_out=False)

    # Get all schools for filter dropdown
    all_schools = School.query.order_by(School.name).all()

    return render_template('superadmin/users.html',
                           pagination=pagination,
                           role_filter=role_filter,
                           school_filter=school_filter,
                           search=search,
                           all_schools=all_schools)


@superadmin_bp.route('/users/<int:user_id>/toggle-active', methods=['POST'])
@role_required('superadmin')
def toggle_user_active(user_id):
    user = User.query.get_or_404(user_id)

    if user.role == 'superadmin':
        flash('Tidak dapat mengubah status superadmin.', 'danger')
        return redirect(url_for('superadmin.users'))

    user.is_active = not user.is_active
    db.session.commit()

    status = 'dinonaktifkan' if not user.is_active else 'diaktifkan'
    flash(f'User "{user.name}" berhasil {status}.', 'success')
    return redirect(url_for('superadmin.users'))


@superadmin_bp.route('/users/<int:user_id>/reset-password', methods=['GET', 'POST'])
@role_required('superadmin')
def reset_user_password(user_id):
    user = User.query.get_or_404(user_id)

    if user.role == 'superadmin':
        flash('Tidak dapat reset password superadmin.', 'danger')
        return redirect(url_for('superadmin.users'))

    if request.method == 'POST':
        new_password = request.form.get('new_password', '')
        confirm_password = request.form.get('confirm_password', '')

        if not new_password or not confirm_password:
            flash('Password baru dan konfirmasi harus diisi.', 'danger')
            return render_template('superadmin/reset_password.html', user=user)

        if new_password != confirm_password:
            flash('Password dan konfirmasi tidak cocok.', 'danger')
            return render_template('superadmin/reset_password.html', user=user)

        if len(new_password) < 6:
            flash('Password minimal 6 karakter.', 'danger')
            return render_template('superadmin/reset_password.html', user=user)

        user.set_password(new_password)
        db.session.commit()
        flash(f'Password untuk "{user.name}" berhasil direset.', 'success')
        return redirect(url_for('superadmin.users'))

    return render_template('superadmin/reset_password.html', user=user)


@superadmin_bp.route('/users/<int:user_id>/delete', methods=['POST'])
@role_required('superadmin')
def delete_user(user_id):
    user = User.query.get_or_404(user_id)

    if user.role == 'superadmin':
        flash('Tidak dapat menghapus superadmin.', 'danger')
        return redirect(url_for('superadmin.users'))

    user_name = user.name
    db.session.delete(user)
    db.session.commit()
    flash(f'User "{user_name}" berhasil dihapus.', 'success')
    return redirect(url_for('superadmin.users'))
