from flask import request
from app.api import api_bp
from app.models.user import User
from app.extensions import db
from app.utils.auth import role_required
from app.utils.response import ok, fail
from app.services.notification_service import create_notification
from app.services.email_service import send_templated_email
from app.models.master import SavingsPlanMember
from app.models.transactions import LoanRequest, CharityRequest, ReleaseRequest
from sqlalchemy import func


@api_bp.get("/admin/users")
@role_required("administrator")
def admin_list_users():
    users = User.query.order_by(User.created_at.desc()).all()
    data = [
        {
            "id": user.id,
            "username": user.username,
            "email": user.email,
            "full_name": user.full_name,
            "mobile_number": user.mobile_number,
            "access_level": user.access_level,
            "account_status": user.account_status,
            "created_at": user.created_at.isoformat(),
        }
        for user in users
    ]
    return ok(data)


@api_bp.put("/admin/users/<int:user_id>")
@role_required("administrator")
def admin_update_user(user_id):
    user = User.query.get_or_404(user_id)
    data = request.json or {}

    account_status = data.get("account_status")
    access_level = data.get("access_level")

    if account_status:
        user.account_status = account_status
    if access_level:
        user.access_level = access_level

    db.session.commit()

    if account_status in ["Approved", "Not Approved"]:
        send_templated_email(
            to=user.email,
            subject=f"Account {account_status}",
            template="emails/account_status_changed.html",
            cc_admin=False,
            full_name=user.full_name,
            status=account_status,
        )
        create_notification(
            user_id=user.id,
            title="Account status updated",
            message=f"Your account status is now {account_status}.",
            notif_type="info" if account_status == "Approved" else "error",
            link="/app/profile",
        )

    return ok({"id": user.id}, "User updated")


@api_bp.delete("/admin/users/<int:user_id>")
@role_required("administrator")
def admin_delete_user(user_id):
    user = User.query.get_or_404(user_id)
    return fail("User deletion is disabled. Use account_status instead.", 409)


@api_bp.get("/admin/dashboard-summary")
@role_required("administrator")
def admin_dashboard_summary():
    total_users = User.query.count()
    active_members = SavingsPlanMember.query.filter_by(status="active").count()
    pending_loans = LoanRequest.query.filter(LoanRequest.status == "pending").count()
    pending_charity = CharityRequest.query.filter(CharityRequest.status == "pending").count()
    pending_release = ReleaseRequest.query.filter(ReleaseRequest.status == "pending").count()
    return ok({
        "total_users": total_users,
        "active_members": active_members,
        "pending_loans": pending_loans,
        "pending_charity": pending_charity,
        "pending_release": pending_release,
    })
