{% extends 'admin/admin_base.html' %}
{% block title %}Пользователи{% endblock %}
{% block admin_content %}
<div class="container-fluid">
    <div class="admin-toolbar">
        <h1 class="admin-toolbar__title"><i class="bi bi-people-fill" aria-hidden="true"></i> Управление пользователями</h1>
        <div class="admin-toolbar__actions">
            <button class="btn btn-success btn-sm" data-bs-toggle="modal" data-bs-target="#addUserModal">
                <i class="bi bi-plus-circle" aria-hidden="true"></i> Добавить пользователя
            </button>
            <button class="btn btn-info btn-sm" onclick="loadLoginHistory()">
                <i class="bi bi-clock-history" aria-hidden="true"></i> История входов
            </button>
            <button class="btn btn-primary btn-sm" onclick="showActiveSessions()">
                <i class="bi bi-person-check" aria-hidden="true"></i> Активные сессии
            </button>
            <button class="btn btn-secondary btn-sm" onclick="showUserGroups()">
                <i class="bi bi-people" aria-hidden="true"></i> Группы пользователей
            </button>
            <a href="{{ url_for('admin.roles_page') }}" class="btn btn-outline-primary btn-sm">
                <i class="bi bi-person-badge" aria-hidden="true"></i> Роли
            </a>
            <button class="btn btn-warning btn-sm" onclick="showActionHistory()">
                <i class="bi bi-journal-text" aria-hidden="true"></i> История действий
            </button>
        </div>
    </div>
    <div class="admin-card">
        <div class="card-header">
            <h5 class="mb-0">Список пользователей</h5>
        </div>
        <div class="admin-table-wrap">
            <div class="table-responsive">
                <table class="admin-table table table-hover align-middle">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Имя пользователя</th>
                                    <th>Email</th>
                                    <th>Verified</th>
                                    <th>Роль</th>
                                    <th>MFA</th>
                                    <th>Статус</th>
                                    <th>Действия</th>
                                </tr>
                            </thead>
                            <tbody id="usersTableBody">
                                {% for user in users %}
                                <tr data-user-id="{{ user.id }}">
                                    <td>{{ user.id }}</td>
                                    <td>
                                        <strong>{{ user.username }}</strong>
                                        {% if user.is_admin %}
                                        <span class="badge bg-danger ms-1">Super Admin</span>
                                        {% endif %}
                                        {% if user.public_api_blocked %}
                                        <span class="badge bg-dark ms-1" title="Public API blocked">PA</span>
                                        {% endif %}
                                    </td>
                                    <td>{{ user.email or '—' }}</td>
                                    <td>
                                        {% if user.email_verified %}
                                        <span class="badge bg-success" title="Email verified"><i class="bi bi-check-circle"></i></span>
                                        {% else %}
                                        <span class="badge bg-warning text-dark" title="Not verified"><i class="bi bi-x-circle"></i></span>
                                        {% endif %}
                                        {% if user.pending_email %}
                                        <small class="text-muted d-block">→ {{ user.pending_email }}</small>
                                        {% endif %}
                                    </td>
                                    <td>
                                        {% if user.role %}
                                        <span class="badge bg-primary">{{ user.role.name }}</span>
                                        {% elif user.is_admin %}
                                        <span class="badge bg-danger">Super Admin</span>
                                        {% else %}
                                        <span class="badge bg-secondary">Пользователь</span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        {% if user.mfa_enabled %}
                                        <span class="badge bg-success"><i class="bi bi-shield-check"></i> Включено</span>
                                        {% else %}
                                        <span class="badge bg-secondary"><i class="bi bi-shield-x"></i> Выключено</span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        {% if user.is_locked %}
                                        <span class="badge bg-danger"><i class="bi bi-lock-fill"></i> Заблокирован</span>
                                        {% else %}
                                        <span class="badge bg-success"><i class="bi bi-unlock-fill"></i> Активен</span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        <div class="btn-group btn-group-sm" role="group">
                                            <button class="btn btn-outline-primary edit-user-btn" 
                                                    data-user-id="{{ user.id }}" 
                                                    data-username="{{ user.username }}" 
                                                    data-email="{{ user.email or '' }}" 
                                                    data-is-admin="{{ user.is_admin|int }}"
                                                    data-role-id="{{ user.role_id or '' }}"
                                                    data-mfa-enabled="{{ user.mfa_enabled|int }}"
                                                    data-is-locked="{{ user.is_locked|int }}"
                                                    data-email-verified="{{ user.email_verified|int }}"
                                                    data-public-api-blocked="{{ user.public_api_blocked|int }}"
                                                    title="Редактировать">
                                                <i class="bi bi-pencil"></i>
                                            </button>
                                            <button class="btn btn-outline-info mfa-manage-btn" 
                                                    data-user-id="{{ user.id }}"
                                                    data-username="{{ user.username }}"
                                                    data-mfa-enabled="{{ user.mfa_enabled|int }}"
                                                    title="Управление MFA">
                                                <i class="bi bi-shield-lock"></i>
                                            </button>
                                            {% if user.is_locked %}
                                            <button class="btn btn-outline-success unlock-user-btn" 
                                                    data-user-id="{{ user.id }}"
                                                    title="Разблокировать">
                                                <i class="bi bi-unlock"></i>
                                            </button>
                                            {% else %}
                                            <button class="btn btn-outline-warning lock-user-btn" 
                                                    data-user-id="{{ user.id }}"
                                                    title="Заблокировать">
                                                <i class="bi bi-lock"></i>
                                            </button>
                                            {% endif %}
                                            <button class="btn btn-outline-secondary resend-verify-btn"
                                                    data-user-id="{{ user.id }}"
                                                    data-username="{{ user.username }}"
                                                    title="Resend verification">
                                                <i class="bi bi-envelope-check"></i>
                                            </button>
                                            <button class="btn btn-outline-danger delete-user-btn" 
                                                    data-user-id="{{ user.id }}"
                                                    title="Удалить">
                                                <i class="bi bi-trash"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                                {% else %}
                                <tr>
                                    <td colspan="8" class="text-center">Пользователи не найдены</td>
                                </tr>
                                {% endfor %}
                            </tbody>
                        </table>
            </div>
        </div>
    </div>
</div>

<!-- Модальное окно для редактирования пользователя -->
<div class="modal fade" id="editUserModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <form id="edit-user-form">
                <div class="modal-header">
                    <h5 class="modal-title">Редактировать пользователя</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div id="edit-user-form-error" class="alert alert-danger d-none" role="alert"></div>
                    <input type="hidden" name="id" id="edit-user-id">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="edit-username" class="form-label">Имя пользователя <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="edit-username" name="username" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="edit-email" class="form-label">Email</label>
                            <input type="email" class="form-control" id="edit-email" name="email">
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="edit-password" class="form-label">Новый пароль</label>
                        <input type="password" class="form-control" id="edit-password" name="password" minlength="6" placeholder="Оставьте пустым, чтобы не менять">
                        <small class="form-text text-muted">Минимум 6 символов</small>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="edit-role" class="form-label">Роль</label>
                            <select class="form-select" id="edit-role" name="role_id">
                                <option value="">Без роли</option>
                                <!-- Роли будут загружены через JS -->
                            </select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Администратор</label>
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" id="edit-is-admin" name="is_admin" value="1">
                                <label class="form-check-label" for="edit-is-admin">Супер-администратор</label>
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Public API</label>
                        <div class="form-check form-switch">
                            <input class="form-check-input" type="checkbox" id="edit-public-api-blocked" name="public_api_blocked">
                            <label class="form-check-label" for="edit-public-api-blocked">Блокировать Public API</label>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Отмена</button>
                    <button type="submit" class="btn btn-primary">Сохранить</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Модальное окно для создания пользователя -->
<div class="modal fade" id="addUserModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <form id="add-user-form">
                <div class="modal-header">
                    <h5 class="modal-title">Добавить пользователя</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div id="add-user-form-error" class="alert alert-danger d-none" role="alert"></div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="add-username" class="form-label">Имя пользователя <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="add-username" name="username" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="add-email" class="form-label">Email</label>
                            <input type="email" class="form-control" id="add-email" name="email">
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="add-password" class="form-label">Пароль <span class="text-danger">*</span></label>
                        <input type="password" class="form-control" id="add-password" name="password" required minlength="6">
                        <small class="form-text text-muted">Минимум 6 символов</small>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="add-role" class="form-label">Роль</label>
                            <select class="form-select" id="add-role" name="role_id">
                                <option value="">Без роли</option>
                                <!-- Роли будут загружены через JS -->
                            </select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Администратор</label>
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" id="add-is-admin" name="is_admin" value="1">
                                <label class="form-check-label" for="add-is-admin">Супер-администратор</label>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Отмена</button>
                    <button type="submit" class="btn btn-success">Создать</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Модальное окно для управления MFA -->
<div class="modal fade" id="mfaModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Управление MFA</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="mfaModalBody">
                <div class="text-center">
                    <div class="spinner-border" role="status"></div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
            </div>
        </div>
    </div>
</div>

<!-- Модальное окно для истории входов -->
<div class="modal fade" id="loginHistoryModal" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">История входов и выходов</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <input type="text" class="form-control" id="historySearchInput" placeholder="Поиск по имени пользователя или IP...">
                </div>
                <div class="admin-table-wrap admin-table-wrap--modal">
                    <table class="admin-table table">
                        <thead>
                            <tr>
                                <th>Дата</th>
                                <th>Пользователь</th>
                                <th>Действие</th>
                                <th>IP адрес</th>
                                <th>Статус</th>
                                <th>Причина ошибки</th>
                            </tr>
                        </thead>
                        <tbody id="loginHistoryBody">
                            <tr>
                                <td colspan="6" class="text-center">
                                    <div class="spinner-border" role="status"></div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
            </div>
        </div>
    </div>
</div>

<!-- Модальное окно для активных сессий -->
<div class="modal fade" id="activeSessionsModal" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Активные сессии</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <input type="text" class="form-control" id="sessionSearchInput" placeholder="Поиск по пользователю, IP или User-Agent..." oninput="filterSessions()">
                </div>
                <div class="admin-table-wrap admin-table-wrap--modal">
                    <table class="admin-table table">
                        <thead>
                            <tr>
                                <th>Пользователь</th>
                                <th>IP адрес</th>
                                <th>User-Agent</th>
                                <th>Создана</th>
                                <th>Активность</th>
                                <th>Истекает</th>
                                <th>Действия</th>
                            </tr>
                        </thead>
                        <tbody id="activeSessionsBody">
                            <tr>
                                <td colspan="7" class="text-center">
                                    <div class="spinner-border" role="status"></div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
            </div>
        </div>
    </div>
</div>

<!-- Модальное окно для групп пользователей -->
<div class="modal fade" id="userGroupsModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Группы пользователей</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="d-flex justify-content-end mb-3">
                    <button type="button" class="btn btn-primary btn-sm" onclick="showCreateGroupModal()">
                        <i class="bi bi-plus-circle"></i> Создать группу
                    </button>
                </div>
                <div id="userGroupsContainer">
                    <div class="text-center">
                        <div class="spinner-border" role="status"></div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
            </div>
        </div>
    </div>
</div>

<!-- Модальное окно для истории действий -->
<div class="modal fade" id="actionHistoryModal" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">История действий пользователей</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="row g-2 mb-3">
                    <div class="col-md-4">
                        <label for="actionTypeFilter" class="form-label">Тип действия</label>
                        <select id="actionTypeFilter" class="form-select" onchange="loadActionHistory()">
                            <option value="">Все</option>
                            <option value="create">create</option>
                            <option value="update">update</option>
                            <option value="delete">delete</option>
                            <option value="login">login</option>
                            <option value="logout">logout</option>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label for="resourceTypeFilter" class="form-label">Тип ресурса</label>
                        <select id="resourceTypeFilter" class="form-select" onchange="loadActionHistory()">
                            <option value="">Все</option>
                            <option value="user">user</option>
                            <option value="role">role</option>
                            <option value="session">session</option>
                            <option value="group">group</option>
                        </select>
                    </div>
                </div>
                <div class="admin-table-wrap admin-table-wrap--modal">
                    <table class="admin-table table">
                        <thead>
                            <tr>
                                <th>Дата</th>
                                <th>Пользователь</th>
                                <th>Действие</th>
                                <th>Ресурс</th>
                                <th>Описание</th>
                                <th>IP</th>
                                <th>Статус</th>
                            </tr>
                        </thead>
                        <tbody id="actionHistoryBody">
                            <tr>
                                <td colspan="7" class="text-center">
                                    <div class="spinner-border" role="status"></div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block admin_scripts %}
<script src="{{ url_for('static', filename='js/csrf-fetch.js') }}"></script>
<script src="{{ url_for('static', filename='js/users.js') }}"></script>
{% endblock %}
