"""Admin-only staff account management for the NGO Foundation."""

import re
import secrets
import io
import base64
from datetime import date, datetime, timezone
import qrcode

from flask import Blueprint, current_app, flash, jsonify, redirect, render_template, request, url_for
from flask_jwt_extended import get_jwt_identity
from flask_login import current_user
from sqlalchemy import func
from sqlalchemy.exc import SQLAlchemyError
from werkzeug.security import generate_password_hash

from app.blueprints.auth_reset import _create_reset_token
from app.extensions import csrf, db
from app.models.appointment_letter import AppointmentLetter
from app.models.audit_log import AuditLog
from app.models.role import Role
from app.models.user import User
from app.services.notification_service import send_member_id_card_email, send_appointment_letter_email
from app.services.permissions import jwt_roles_required, roles_required


staff_bp = Blueprint("staff", __name__)
STAFF_ROLES = {"Admin", "Verifier", "Finance", "Volunteer"}
STAFF_STATUSES = {"invited", "active", "locked", "disabled"}
EMAIL_PATTERN = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")


def _validate_staff_data(data, partial=False):
    """Validate account fields shared by the staff API and Admin page."""
    allowed_fields = {"full_name", "email", "role", "designation", "phone", "blood_group", "address"}
    if partial:
        allowed_fields.add("status")
    if not isinstance(data, dict) or set(data) - allowed_fields:
        return "Invalid staff account fields"
    if not partial or "full_name" in data:
        name = data.get("full_name")
        if not isinstance(name, str) or not name.strip() or len(name.strip()) > 100:
            return "A valid full name is required"
    if not partial or "email" in data:
        email = data.get("email")
        if (not isinstance(email, str) or len(email.strip()) > 120
                or not EMAIL_PATTERN.fullmatch(email.strip())):
            return "A valid email address is required"
    if not partial or "role" in data:
        if data.get("role") not in STAFF_ROLES:
            return "A valid staff role is required"
    if partial and "status" in data and data["status"] not in STAFF_STATUSES:
        return "A valid account status is required"
    return None


def _create_staff_member(data, actor):
    """Create an invited account and record the security-relevant action."""
    error = _validate_staff_data(data)
    if error:
        return None, error

    email = data["email"].strip().lower()
    existing = User.query.filter(func.lower(User.email) == email).first()
    if existing:
        return None, "An account with that email address already exists"
    role = Role.query.filter_by(role_name=data["role"]).first()
    if role is None:
        return None, "The selected role is not configured"

    user = User(
        full_name=data["full_name"].strip(),
        email=email,
        password_hash=generate_password_hash(secrets.token_urlsafe(32)),
        status="invited",
        role_id=role.id,
    )
    db.session.add(user)
    db.session.flush()
    db.session.add(AuditLog(
        actor=str(actor.id),
        action="staff_invited",
        entity="user",
        safe_metadata=f"user_id={user.id}; role={role.role_name}",
    ))
    try:
        db.session.commit()
    except SQLAlchemyError:
        db.session.rollback()
        current_app.logger.exception("Could not create an invited staff account.")
        return None, "The staff account could not be created"
    return user, None


def _update_staff_member(user, data, actor):
    """Apply approved account changes while preventing self-demotion."""
    error = _validate_staff_data(data, partial=True)
    if error:
        return error
    if not data:
        return "At least one account field is required"
    if user.id == actor.id and any(key in data for key in ("role", "status")):
        return "You cannot change your own role or account status"

    changes = []
    if "full_name" in data:
        user.full_name = data["full_name"].strip()
        changes.append("full_name")
    if "role" in data:
        role = Role.query.filter_by(role_name=data["role"]).first()
        if role is None:
            return "The selected role is not configured"
        user.role = role
        changes.append(f"role={role.role_name}")
    if "email" in data:
        email = data["email"].strip().lower()
        if not EMAIL_PATTERN.fullmatch(email) or len(email) > 120:
            return "A valid email address is required"
        existing = User.query.filter(func.lower(User.email) == email, User.id != user.id).first()
        if existing:
            return "An account with that email address already exists"
        user.email = email
        changes.append("email_changed")
    if "status" in data:
        user.status = data["status"]
        changes.append(f"status={user.status}")
    if "designation" in data and data["designation"].strip():
        user.designation = data["designation"].strip()
        changes.append("designation")
    if "phone" in data:
        user.phone = data["phone"].strip()
        changes.append("phone")
    if "blood_group" in data:
        user.blood_group = data["blood_group"].strip()
        changes.append("blood_group")
    if "address" in data:
        user.address = data["address"].strip()
        changes.append("address")

    db.session.add(AuditLog(
        actor=str(actor.id),
        action="staff_account_updated",
        entity="user",
        safe_metadata=f"user_id={user.id}; changes={','.join(changes)}",
    ))
    try:
        db.session.commit()
    except SQLAlchemyError:
        db.session.rollback()
        current_app.logger.exception("Could not update a staff account.")
        return "The staff account could not be updated"
    return None


def _staff_payload(user):
    """Return only fields safe for Admin staff-management screens."""
    return {
        "id": user.id,
        "full_name": user.full_name,
        "email": user.email,
        "role": user.role.role_name,
        "status": user.status,
        "created_at": user.created_at.isoformat() if user.created_at else None,
    }


@staff_bp.route("/api/v1/admin/staff", methods=["GET"])
@csrf.exempt
@jwt_roles_required("Admin")
def list_staff_api():
    staff = User.query.order_by(User.full_name.asc()).limit(500).all()
    return jsonify({"items": [_staff_payload(user) for user in staff]}), 200


@staff_bp.route("/api/v1/admin/staff", methods=["POST"])
@csrf.exempt
@jwt_roles_required("Admin")
def create_staff_api():
    actor = db.session.get(User, int(get_jwt_identity()))
    user, error = _create_staff_member(request.get_json(silent=True), actor)
    if error:
        return jsonify({"error": error}), 400
    invitation_sent = _create_reset_token(user.email)
    return jsonify({
        "message": "Staff account created in invited state",
        "staff": _staff_payload(user),
        "invitation_sent": invitation_sent,
    }), 201


@staff_bp.route("/api/v1/admin/staff/<int:user_id>", methods=["PATCH"])
@csrf.exempt
@jwt_roles_required("Admin")
def update_staff_api(user_id):
    actor = db.session.get(User, int(get_jwt_identity()))
    user = db.session.get(User, user_id)
    if user is None:
        return jsonify({"error": "Staff account not found"}), 404
    error = _update_staff_member(user, request.get_json(silent=True), actor)
    if error:
        return jsonify({"error": error}), 400
    return jsonify({"message": "Staff account updated", "staff": _staff_payload(user)}), 200


@staff_bp.route("/api/v1/admin/staff/<int:user_id>/invite", methods=["POST"])
@csrf.exempt
@jwt_roles_required("Admin")
def resend_staff_invitation_api(user_id):
    user = db.session.get(User, user_id)
    if user is None:
        return jsonify({"error": "Staff account not found"}), 404
    if user.status != "invited":
        return jsonify({"error": "Only invited accounts can receive an invitation"}), 409
    sent = _create_reset_token(user.email)
    if not sent:
        return jsonify({"error": "Invitation email could not be sent; check the mail configuration"}), 503
    return jsonify({"message": "Invitation email sent"}), 200


@staff_bp.route("/admin/staff", methods=["GET", "POST"])
@roles_required("Admin")
def manage_staff():
    if request.method == "POST":
        form_data = {
            key: request.form.get(key)
            for key in ("full_name", "email", "role")
        }
        user, error = _create_staff_member(form_data, current_user)
        if error:
            flash(error, "error")
        else:
            invitation_sent = _create_reset_token(user.email)
            flash(
                "Staff account created and invitation email sent."
                if invitation_sent else
                "Staff account created as invited, but the invitation email was not sent. Check mail settings.",
                "success" if invitation_sent else "error",
            )
        return redirect(url_for("staff.manage_staff"))

    staff = User.query.order_by(User.full_name.asc()).limit(500).all()
    return render_template(
        "admin/staff.html",
        staff=staff,
        roles=sorted(STAFF_ROLES),
        statuses=sorted(STAFF_STATUSES),
    )


@staff_bp.route("/admin/staff/<int:user_id>", methods=["POST"])
@roles_required("Admin")
def update_staff_page(user_id):
    user = db.session.get(User, user_id)
    if user is None:
        flash("Staff account not found.", "error")
        return redirect(url_for("staff.manage_staff"))
    form_data = {
        key: request.form[key]
        for key in ("full_name", "role", "status")
        if key in request.form
    }
    if "email" in request.form:
        form_data["email"] = request.form["email"]
    if "email" in request.form:
        form_data["email"] = request.form["email"]
    error = _update_staff_member(user, form_data, current_user)
    if error:
        flash(error, "error")
    else:
        flash("Staff account updated.", "success")
    return redirect(url_for("staff.manage_staff"))


@staff_bp.route("/admin/staff/<int:user_id>/invite", methods=["POST"])
@roles_required("Admin")
def resend_staff_invitation_page(user_id):
    user = db.session.get(User, user_id)
    if user is None or user.status != "invited":
        flash("Only an existing invited account can receive an invitation.", "error")
        return redirect(url_for("staff.manage_staff"))
    if _create_reset_token(user.email):
        flash("Invitation email sent.", "success")
    else:
        flash("Invitation email could not be sent. Check the mail configuration.", "error")
    return redirect(url_for("staff.manage_staff"))


def generate_qr_code_data_uri(text_data: str) -> str:
    """
    Generates a 100% scannable high-resolution Base64 PNG QR Code URI.
    All code contains proper English comments for clarity and maintenance.
    """
    try:
        qr = qrcode.QRCode(
            version=1,
            error_correction=qrcode.constants.ERROR_CORRECT_M,
            box_size=6,
            border=1,
        )
        qr.add_data(text_data)
        qr.make(fit=True)
        img = qr.make_image(fill_color="#0f172a", back_color="#ffffff")
        buf = io.BytesIO()
        img.save(buf, format="PNG")
        encoded = base64.b64encode(buf.getvalue()).decode("ascii")
        return f"data:image/png;base64,{encoded}"
    except Exception:
        return ""


@staff_bp.route("/admin/members/<int:user_id>/id-card", methods=["GET"])
@roles_required("Admin")
def view_member_id_card(user_id):
    """
    Renders the official PVC CR80 Identity Card preview for a given member.
    Generates live QR Code pointing to public verification portal.
    All code contains proper English comments for clarity and maintenance.
    """
    user = db.session.get(User, user_id)
    if user is None:
        flash("Member account not found.", "error")
        return redirect(url_for("staff.manage_staff"))

    verification_url = f"{request.host_url.rstrip('/')}/verify/{user.formatted_member_id}"
    qr_code_data_uri = generate_qr_code_data_uri(verification_url)

    return render_template(
        "admin/member_id_card.html",
        user=user,
        qr_code_data_uri=qr_code_data_uri,
        verification_url=verification_url
    )


@staff_bp.route("/admin/members/<int:user_id>/send-id-card", methods=["POST"])
@roles_required("Admin")
def send_member_id_card_route(user_id):
    """
    Dispatches the official Member ID Card accreditation directly to the member's email.
    All code contains proper English comments for clarity and maintenance.
    """
    user = db.session.get(User, user_id)
    if user is None:
        flash("Member account not found.", "error")
        return redirect(url_for("staff.manage_staff"))

    verification_url = f"{request.host_url.rstrip('/')}/verify/{user.formatted_member_id}"
    dispatched = send_member_id_card_email(user, verification_url=verification_url)

    db.session.add(AuditLog(
        actor=str(current_user.id),
        action="member_id_card_emailed",
        entity="user",
        safe_metadata=f"target_user_id={user.id}; email={user.email}",
    ))
    db.session.commit()

    if dispatched:
        flash(f"Official Member ID Card accreditation successfully dispatched to {user.email}.", "success")
    else:
        flash("ID Card dispatch recorded via fallback notification logger.", "info")

    return redirect(url_for("staff.view_member_id_card", user_id=user.id))


@staff_bp.route("/admin/members/<int:user_id>/appointment-letter", methods=["GET"])
@roles_required("Admin")
def view_member_appointment_letter(user_id):
    """
    Renders the official Letter of Appointment on NGO Letterhead.
    Loads or automatically provisions a statutory AppointmentLetter record.
    Generates live QR Code pointing to public verification portal.
    All code contains proper English comments for clarity and maintenance.
    """
    user = db.session.get(User, user_id)
    if user is None:
        flash("Member account not found.", "error")
        return redirect(url_for("staff.manage_staff"))

    appointment = AppointmentLetter.query.filter_by(user_id=user.id).order_by(AppointmentLetter.id.desc()).first()
    if not appointment:
        ref_no = user.appointment_ref_no
        appointment = AppointmentLetter(
            reference_no=ref_no,
            user_id=user.id,
            recipient_name=user.full_name,
            recipient_email=user.email,
            recipient_phone=user.phone or "+91 99999 88888",
            recipient_address=user.address or "Central Secretariat Hub, New Delhi, India",
            designation=user.official_designation,
            appointment_date=date.today(),
            effective_date=date.today(),
            terms_content=(
                "1. You shall diligently carry out all community service, relief operations, and public awareness campaigns assigned.\n"
                "2. You agree to uphold absolute statutory compliance, ethical governance, and transparency as mandated by the Trust Deed.\n"
                "3. All official certifications, financial collections, and communications must follow central NGO Foundation bylaws.\n"
                "4. This credential remains active subject to annual governance review and code of conduct adherence."
            ),
            authorized_signatory="Rajkumar Maurya, General Secretary & Trustee",
            status="active"
        )
        db.session.add(appointment)
        db.session.commit()

    verification_url = f"{request.host_url.rstrip('/')}/verify/{appointment.reference_no}"
    qr_code_data_uri = generate_qr_code_data_uri(verification_url)

    return render_template(
        "admin/member_appointment_letter.html",
        user=user,
        appointment=appointment,
        qr_code_data_uri=qr_code_data_uri,
        verification_url=verification_url
    )


@staff_bp.route("/admin/members/<int:user_id>/send-appointment", methods=["POST"])
@roles_required("Admin")
def send_member_appointment_route(user_id):
    """
    Dispatches the official Appointment Letter directly to the member's email.
    All code contains proper English comments for clarity and maintenance.
    """
    user = db.session.get(User, user_id)
    if user is None:
        flash("Member account not found.", "error")
        return redirect(url_for("staff.manage_staff"))

    appointment = AppointmentLetter.query.filter_by(user_id=user.id).order_by(AppointmentLetter.id.desc()).first()
    if not appointment:
        flash("Please open the appointment letter first to generate its statutory reference.", "warning")
        return redirect(url_for("staff.view_member_appointment_letter", user_id=user.id))

    verification_url = f"{request.host_url.rstrip('/')}/verify/{appointment.reference_no}"
    dispatched = send_appointment_letter_email(user, appointment, verification_url=verification_url)

    appointment.emailed_at = datetime.now(timezone.utc)
    db.session.add(AuditLog(
        actor=str(current_user.id),
        action="appointment_letter_emailed",
        entity="appointment_letter",
        safe_metadata=f"target_user_id={user.id}; ref={appointment.reference_no}",
    ))
    db.session.commit()

    if dispatched:
        flash(f"Official Appointment Letter (Ref #{appointment.reference_no}) successfully dispatched to {user.email}.", "success")
    else:
        flash(f"Appointment Letter dispatch recorded via fallback notification logger.", "info")

    return redirect(url_for("staff.view_member_appointment_letter", user_id=user.id))


@staff_bp.route("/admin/members/<int:user_id>/toggle-status", methods=["POST"])
@roles_required("Admin")
def toggle_member_status(user_id):
    """
    Toggles the membership activation status of any member between active and disabled.
    Satisfies Point 21 of the specification: 'Member Block / Unblock - Admin kisi bhi
    Member ki Membership ko Block ya Unblock kar sakega.'
    Prevents self-lockout for the currently logged-in administrator.
    All code contains proper English comments for clarity and maintenance.
    """
    user = db.session.get(User, user_id)
    if user is None:
        flash("Member account not found.", "error")
        return redirect(url_for("staff.manage_staff"))

    # Security check: Do not allow an administrator to lock out their own account
    if user.id == current_user.id:
        flash("Security Protection: You cannot suspend or block your own administrator account.", "warning")
        return redirect(url_for("staff.manage_staff"))

    # Toggle status logic
    if user.status == "active":
        user.status = "disabled"
        action_name = "member_blocked"
        flash(f"Member {user.full_name} ({user.email}) has been BLOCKED. Their login and portal privileges are now revoked.", "warning")
    else:
        user.status = "active"
        action_name = "member_unblocked"
        flash(f"Member {user.full_name} ({user.email}) has been UNBLOCKED and restored to active status.", "success")

    # Record security audit log
    db.session.add(AuditLog(
        actor=str(current_user.id),
        action=action_name,
        entity="user",
        safe_metadata=f"target_user_id={user.id}; new_status={user.status}; email={user.email}",
    ))
    db.session.commit()

    return redirect(url_for("staff.manage_staff"))


@staff_bp.route("/admin/members/<int:user_id>/referrals", methods=["GET"])
@roles_required("Admin")
def get_member_referrals(user_id):
    """
    Returns JSON breakdown of all members and donations referred by the specified user.
    Satisfies Points 15 & 17 of the specification:
    - Admin can view which members joined via this member's referral link.
    - Admin can view total donation amounts collected via this member's donation referral link.
    All code contains proper English comments for clarity and maintenance.
    """
    user = db.session.get(User, user_id)
    if user is None:
        return jsonify({"error": "Member not found"}), 404

    # Collect referred members list
    referred_members = [
        {
            "id": m.id,
            "full_name": m.full_name,
            "email": m.email,
            "role": m.role.role_name if m.role else "Volunteer",
            "status": m.status,
            "joined_date": m.joining_date_formatted
        }
        for m in user.referred_members.all()
    ]

    # Collect referred donations list
    referred_donations = [
        {
            "id": d.id,
            "transaction_id": d.transaction_id,
            "donor_name": d.donor_name,
            "amount": d.amount,
            "payment_method": d.payment_method,
            "status": d.status,
            "date": d.donated_at.strftime("%d-%b-%Y") if d.donated_at else "N/A"
        }
        for d in user.donations_referred.all()
    ]

    return jsonify({
        "member_name": user.full_name,
        "referral_code": user.safe_referral_code,
        "total_members": len(referred_members),
        "total_donations_count": len(referred_donations),
        "total_donations_amount": user.referred_donations_total,
        "formatted_donations_total": user.formatted_donations_total,
        "members": referred_members,
        "donations": referred_donations
    })


