"""Admin-only: subordinate management."""
import re

from flask import Blueprint, flash, redirect, render_template, request, url_for
from flask_login import current_user

from . import storage
from .auth import admin_required

admin_bp = Blueprint("admin", __name__, url_prefix="/admin")

EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")


@admin_bp.route("/subordinates")
@admin_required
def subordinates():
    subs = storage.get_subordinates(lead_id=current_user.id, include_inactive=True)
    return render_template("admin/subordinates.html", subordinates=subs)


@admin_bp.route("/subordinates/add", methods=["POST"])
@admin_required
def add_subordinate():
    name = (request.form.get("name") or "").strip()
    email = (request.form.get("email") or "").strip().lower()
    existing = storage.get_user_by_email(email)

    if not name:
        flash("Please enter a name.", "error")
    elif not EMAIL_RE.match(email):
        flash("Please enter a valid Gmail/Google email address.", "error")
    elif existing is not None:
        own = existing["role"] == "subordinate" and existing.get("lead_id") == current_user.id
        if own and not existing.get("active", True):
            storage.update_user(existing["id"], active=True, name=name)
            flash(f"{name} re-activated.", "success")
        elif own:
            flash("That person is already on your team.", "error")
        else:
            flash("That email already belongs to another account.", "error")
    else:
        storage.create_user(email, name, "subordinate", lead_id=current_user.id)
        flash(f"{name} added. They can now sign in with Google.", "success")

    return redirect(url_for("admin.subordinates"))


@admin_bp.route("/subordinates/<int:user_id>/toggle", methods=["POST"])
@admin_required
def toggle_subordinate(user_id):
    user = storage.get_user(user_id)
    if user is None or user["role"] != "subordinate" or user.get("lead_id") != current_user.id:
        flash("Subordinate not found.", "error")
    else:
        new_active = not user.get("active", True)
        storage.update_user(user_id, active=new_active)
        flash(
            f"{user['name']} {'re-activated' if new_active else 'deactivated'}.",
            "success",
        )
    return redirect(url_for("admin.subordinates"))
