from flask import jsonify, render_template, request

from app.admin import admin_blueprint
from app.admin.auth import admin_login_required
from config.db_config import get_db_connection
from werkzeug.security import generate_password_hash


@admin_blueprint.route("/api/users/add", methods=["POST"])
@admin_login_required
def add_user():
    """Add a new user to users_auth table."""
    payload = request.get_json(silent=True) or {}
    username = (payload.get("username") or "").strip()
    password = (payload.get("password") or "").strip()
    name = (payload.get("name") or "").strip()
    email = (payload.get("email") or "").strip()
    phone = (payload.get("phone") or "").strip()
    role = (payload.get("role") or "photographer").strip()

    if not username:
        return jsonify({"error": "Username is required."}), 400
    if not password or len(password) < 6:
        return jsonify({"error": "Password must be at least 6 characters."}), 400
    if role not in ["admin", "photographer"]:
        return jsonify({"error": "Invalid role."}), 400

    connection = None
    cursor = None
    try:
        hashed_password = generate_password_hash(password)
        connection = get_db_connection()
        cursor = connection.cursor()
        cursor.execute(
            "INSERT INTO users_auth (username, password, name, email, phone, role) VALUES (%s, %s, %s, %s, %s, %s)",
            (username, hashed_password, name or None, email or None, phone or None, role)
        )
        connection.commit()
        return jsonify({"success": True, "message": f"User '{username}' created.", "user_id": cursor.lastrowid})
    except Exception as exc:
        err = str(exc)
        if "Duplicate entry" in err:
            return jsonify({"error": f"Username '{username}' already exists."}), 409
        return jsonify({"error": f"Failed to create user: {err}"}), 500
    finally:
        if cursor: cursor.close()
        if connection and connection.is_connected(): connection.close()


@admin_blueprint.route("/users", methods=["GET"])
@admin_login_required
def users_list():
    """Display all users from users_auth table."""
    connection = None
    cursor = None

    try:
        connection = get_db_connection()
        cursor = connection.cursor(dictionary=True)

        cursor.execute(
            "SELECT id, username, email, password, role, name, phone, created_at FROM users_auth ORDER BY id ASC"
        )
        users = cursor.fetchall()

        # Mask passwords for display (show only first 10 chars of hash)
        for user in users:
            if user.get("password"):
                user["password_masked"] = user["password"][:20] + "..."
            else:
                user["password_masked"] = "Not set"

        return render_template("users.html", users=users)

    except Exception as exc:
        return render_template("users.html", users=[], error=str(exc))

    finally:
        if cursor:
            cursor.close()
        if connection and connection.is_connected():
            connection.close()


@admin_blueprint.route("/api/users/<int:user_id>/password", methods=["POST"])
@admin_login_required
def update_user_password(user_id):
    """Update password for a specific user."""
    payload = request.get_json(silent=True) or {}
    new_password = (payload.get("password") or "").strip()

    if not new_password:
        return jsonify({"error": "Password is required."}), 400

    if len(new_password) < 6:
        return jsonify({"error": "Password must be at least 6 characters."}), 400

    connection = None
    cursor = None

    try:
        # Hash the new password
        hashed_password = generate_password_hash(new_password)

        # Update in database
        connection = get_db_connection()
        cursor = connection.cursor()

        cursor.execute(
            "UPDATE users_auth SET password = %s WHERE id = %s",
            (hashed_password, user_id)
        )
        connection.commit()

        if cursor.rowcount == 0:
            return jsonify({"error": "User not found."}), 404

        return jsonify({
            "success": True,
            "message": "Password updated successfully.",
            "user_id": user_id
        })

    except Exception as exc:
        return jsonify({"error": f"Failed to update password: {exc}"}), 500

    finally:
        if cursor:
            cursor.close()
        if connection and connection.is_connected():
            connection.close()


@admin_blueprint.route("/api/users/<int:user_id>/role", methods=["POST"])
@admin_login_required
def update_user_role(user_id):
    """Update role for a specific user."""
    payload = request.get_json(silent=True) or {}
    new_role = (payload.get("role") or "").strip()

    if not new_role:
        return jsonify({"error": "Role is required."}), 400

    if new_role not in ["admin", "photographer"]:
        return jsonify({"error": "Invalid role. Must be 'admin' or 'photographer'."}), 400

    connection = None
    cursor = None

    try:
        connection = get_db_connection()
        cursor = connection.cursor()

        cursor.execute(
            "UPDATE users_auth SET role = %s WHERE id = %s",
            (new_role, user_id)
        )
        connection.commit()

        if cursor.rowcount == 0:
            return jsonify({"error": "User not found."}), 404

        return jsonify({
            "success": True,
            "message": "Role updated successfully.",
            "user_id": user_id,
            "new_role": new_role
        })

    except Exception as exc:
        return jsonify({"error": f"Failed to update role: {exc}"}), 500

    finally:
        if cursor:
            cursor.close()
        if connection and connection.is_connected():
            connection.close()


@admin_blueprint.route("/api/users/<int:user_id>", methods=["DELETE"])
@admin_login_required
def delete_user(user_id):
    """Delete a user from users_auth table."""
    connection = None
    cursor = None

    try:
        connection = get_db_connection()
        cursor = connection.cursor()

        # Prevent admin from deleting themselves
        from flask import session
        if session.get("user_id") == user_id:
            return jsonify({"error": "Cannot delete your own account."}), 403

        cursor.execute("DELETE FROM users_auth WHERE id = %s", (user_id,))
        connection.commit()
        result = cursor.fetchone()

        if result is None:
            return jsonify({"error": "User not found."}), 404

        return jsonify({
            "success": True,
            "message": "User deleted successfully.",
            "user_id": user_id
        })

    except Exception as exc:
        return jsonify({"error": f"Failed to delete user: {exc}"}), 500

    finally:
        if cursor:
            cursor.close()
        if connection and connection.is_connected():
            connection.close()