{% extends "base.html" %}

{% block title %}Bedrock Server Manager - Users{% endblock %}

{% block head_scripts %}
    <script src="{{ request.url_for('static', path='js/utils.js') }}" defer></script>
    <script src="{{ request.url_for('static', path='js/sidebar_nav.js') }}" defer></script>
{% endblock %}

{% block content %}
<div class="page-layout">
    <aside class="sidebar-nav">
        <a href="#user-management-section" class="nav-link active" data-target="user-management-section">User Management</a>
        <div class="nav-item">
            <a href="#" class="nav-link has-submenu">Users</a>
            <div class="submenu">
                {% for user in users %}
                    <a href="#user-{{ user.id }}-section" class="nav-link" data-target="user-{{ user.id }}-section">{{ user.username }}</a>
                {% endfor %}
            </div>
        </div>
        <hr class="nav-separator">
        <a href="{{ url_for('index') }}" class="nav-link nav-action-button">Dashboard</a>
    </aside>

    <main class="main-content">
        <section id="user-management-section" class="content-section active">
            <h2>User Management</h2>
            {% if current_user.role == 'admin' %}
            <h3>Generate Registration Link</h3>
            <form id="generate-token-form">
                <div class="form-group">
                    <label for="role">Role</label>
                    <select id="role" name="role" class="form-input">
                        <option value="user">User</option>
                        <option value="moderator">Moderator</option>
                        <option value="admin">Admin</option>
                    </select>
                </div>
                <button type="button" class="action-button" onclick="generateToken()">Generate Link</button>
            </form>

            {% if 'message' in request.query_params and 'Registration link generated' in request.query_params['message'] %}
            <div class="message-box">
                <p>{{ request.query_params['message'] }}</p>
                <button class="action-button" onclick="copyToClipboard('{{ request.query_params['message'].split(': ')[1] }}')">Copy Link</button>
            </div>
            {% endif %}
            {% endif %}
        </section>

        {% for user in users %}
        <section id="user-{{ user.id }}-section" class="content-section">
            <h2>{{ user.username }}</h2>
            <div class="server-card-info">
                <p><span class="info-label">Role:</span> {{ user.role }}</p>
                {% if user.last_seen %}
                <p><span class="info-label">Last Seen:</span> {{ user.last_seen.strftime('%Y-%m-%d %H:%M:%S') }} UTC</p>
                {% endif %}
            </div>
            <div class="server-card-actions">
                {% if current_user.role == 'admin' %}
                <div class="form-group">
                    <label for="role-{{ user.id }}">Role</label>
                    <select id="role-{{ user.id }}" name="role" class="form-input">
                        <option value="user" {% if user.role == 'user' %}selected{% endif %}>User</option>
                        <option value="moderator" {% if user.role == 'moderator' %}selected{% endif %}>Moderator</option>
                        <option value="admin" {% if user.role == 'admin' %}selected{% endif %}>Admin</option>
                    </select>
                </div>
                <button type="button" class="action-button" onclick="updateUserRole('{{ user.id }}')">Save</button>
                {% if user.is_active %}
                <button type="button" class="warning-button" onclick="disableUser('{{ user.id }}')">Disable</button>
                {% else %}
                <button type="button" class="success-button" onclick="enableUser('{{ user.id }}')">Enable</button>
                {% endif %}
                <button type="button" class="danger-button" onclick="deleteUser('{{ user.id }}')">Delete</button>
                {% endif %}
            </div>
        </section>
        {% endfor %}
    </main>
</div>
{% endblock %}

{% block body_scripts %}
<script>
function copyToClipboard(text) {
    navigator.clipboard.writeText(text).then(function() {
        alert('Copied to clipboard');
    }, function(err) {
        alert('Could not copy text: ', err);
    });
}

function generateToken() {
    const form = document.getElementById('generate-token-form');
    const formData = new FormData(form);
    const data = Object.fromEntries(formData.entries());

    sendServerActionRequest(null, "/register/generate-token", 'POST', data)
        .then(response => {
            if (response && response.status === 'success') {
                window.location.href = response.redirect_url;
            }
        });
}

function disableUser(userId) {
    if (confirm('Are you sure you want to disable this user?')) {
        sendServerActionRequest(null, `/users/${userId}/disable`, 'POST')
            .then(response => {
                if (response && response.status === 'success') {
                    window.location.reload();
                }
            });
    }
}

function enableUser(userId) {
    if (confirm('Are you sure you want to enable this user?')) {
        sendServerActionRequest(null, `/users/${userId}/enable`, 'POST')
            .then(response => {
                if (response && response.status === 'success') {
                    window.location.reload();
                }
            });
    }
}

function deleteUser(userId) {
    if (confirm('Are you sure you want to delete this user?')) {
        sendServerActionRequest(null, `/users/${userId}/delete`, 'POST')
            .then(response => {
                if (response && response.status === 'success') {
                    window.location.reload();
                }
            });
    }
}

function updateUserRole(userId) {
    const role = document.getElementById(`role-${userId}`).value;
    const data = { role: role };

    sendServerActionRequest(null, `/users/${userId}/role`, 'POST', data)
        .then(response => {
            if (response && response.status === 'success') {
                window.location.reload();
            }
        });
}
</script>
{% endblock %}
