<!DOCTYPE html>
<html lang="en" class="dark">
<head>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>Admin Dashboard</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap"
          rel="stylesheet">
    <style>
        body {
            font-family: 'Poppins', sans-serif;
        }

        .modal {
            display: none;
        }

        .modal.active {
            display: flex;
        }
    </style>
</head>
<body class="bg-gray-900 text-gray-200">

<div class="container mx-auto p-8">
    <h1 class="text-4xl font-bold text-white mb-8">Admin Dashboard</h1>

    <div class="bg-gray-800 p-6 rounded-lg shadow-lg mb-8">
        <h2 class="text-2xl font-semibold text-white mb-4">User Management</h2>
        <div class="mb-4">
            <input type="text" id="user-search" placeholder="Search by username or email..."
                   class="w-full bg-gray-700 text-white p-3 rounded-lg border border-gray-600 focus:outline-none focus:ring-2 focus:ring-indigo-500">
        </div>
        <div class="overflow-x-auto">
            <table class="min-w-full bg-gray-700 rounded-lg">
                <thead>
                <tr>
                    <th class="p-3 text-left">Username</th>
                    <th class="p-3 text-left">Email</th>
                    <th class="p-3 text-center">Status</th>
                    <th class="p-3 text-center">Actions</th>
                </tr>
                </thead>
                <tbody id="user-table-body">
                </tbody>
            </table>
        </div>
    </div>

    <div class="bg-gray-800 p-6 rounded-lg shadow-lg">
        <h2 class="text-2xl font-semibold text-white mb-4">Role Management</h2>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
                <h3 class="text-lg font-medium text-white mb-2">Existing Roles</h3>
                <ul id="role-list" class="space-y-2">
                </ul>
            </div>
            <div>
                <h3 class="text-lg font-medium text-white mb-2">Create New Role</h3>
                <form id="create-role-form" class="space-y-4">
                    <input type="text" id="role-name" placeholder="Role Name" required
                           class="w-full bg-gray-700 text-white p-3 rounded-lg border border-gray-600">
                    <input type="text" id="role-description" placeholder="Description"
                           class="w-full bg-gray-700 text-white p-3 rounded-lg border border-gray-600">
                    <input type="number" id="role-level" placeholder="Hierarchy Level (e.g., 90)"
                           class="w-full bg-gray-700 text-white p-3 rounded-lg border border-gray-600">
                    <button type="submit"
                            class="w-full bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-3 px-4 rounded-lg transition-colors">
                        Create Role
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

<div id="assign-role-modal" class="modal fixed inset-0 bg-black bg-opacity-75 items-center justify-center">
    <div class="bg-gray-800 p-8 rounded-lg shadow-2xl w-full max-w-md">
        <h2 class="text-2xl font-semibold text-white mb-6">Assign Role to <span id="modal-username"></span></h2>
        <input type="hidden" id="modal-user-id">
        <div class="space-y-4">
            <select id="modal-role-select" class="w-full bg-gray-700 text-white p-3 rounded-lg border border-gray-600">
            </select>
            <input type="text" id="modal-scope-input" placeholder="Scope (e.g., global)" value="global"
                   class="w-full bg-gray-700 text-white p-3 rounded-lg border border-gray-600">
        </div>
        <div class="mt-8 flex justify-end space-x-4">
            <button onclick="closeModal()"
                    class="bg-gray-600 hover:bg-gray-700 text-white font-bold py-2 px-6 rounded-lg">Cancel
            </button>
            <button onclick="submitAssignRole()"
                    class="bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-2 px-6 rounded-lg">Assign
            </button>
        </div>
    </div>
</div>

<div id="toast"
     class="fixed bottom-8 right-8 bg-green-500 text-white py-3 px-6 rounded-lg shadow-lg transform translate-y-20 opacity-0 transition-all duration-300">
    <p id="toast-message"></p>
</div>

<script>
    // --- Initial Data ---
    let allRoles = [];

    // --- DOM Elements ---
    const userSearchInput = document.getElementById('user-search');
    const userTableBody = document.getElementById('user-table-body');
    const roleList = document.getElementById('role-list');
    const createRoleForm = document.getElementById('create-role-form');
    const modal = document.getElementById('assign-role-modal');
    const modalUserId = document.getElementById('modal-user-id');
    const modalUsername = document.getElementById('modal-username');
    const modalRoleSelect = document.getElementById('modal-role-select');
    const toast = document.getElementById('toast');
    const toastMessage = document.getElementById('toast-message');

    // --- API Functions ---
    async function apiRequest(endpoint, method = 'GET', body = null) {
        const options = {
            method,
            headers: {'Content-Type': 'application/json'},
        };
        if (body) {
            options.body = JSON.stringify(body);
        }
        const response = await fetch(`/admin${endpoint}`, options);
        if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.detail || 'An API error occurred');
        }
        return response.status !== 204 ? await response.json() : null;
    }

    // --- UI Functions ---
    function showToast(message, isError = false) {
        toastMessage.textContent = message;
        toast.className = `fixed bottom-8 right-8 text-white py-3 px-6 rounded-lg shadow-lg transform transition-all duration-300 ${isError ? 'bg-red-500' : 'bg-green-500'} translate-y-0 opacity-100`;
        setTimeout(() => {
            toast.className = toast.className.replace('translate-y-0 opacity-100', 'translate-y-20 opacity-0');
        }, 3000);
    }

    function renderUsers(users) {
        userTableBody.innerHTML = users.map(user => `
                <tr class="border-b border-gray-600">
                    <td class="p-3">${user.username}</td>
                    <td class="p-3">${user.email}</td>
                    <td class="p-3 text-center">
                        <span class="${user.is_active ? 'bg-green-500' : 'bg-red-500'} text-white text-xs font-semibold mr-2 px-2.5 py-0.5 rounded-full">
                            ${user.is_active ? 'Active' : 'Suspended'}
                        </span>
                    </td>
                    <td class="p-3 text-center space-x-2">
    <a href="/admin/users/${user.id}" class="bg-gray-600 hover:bg-gray-700 text-white text-sm font-bold py-1 px-3 rounded">View</a>
    <button onclick="openAssignRoleModal('${user.id}', '${user.username}')" class="bg-blue-600 hover:bg-blue-700 text-white text-sm font-bold py-1 px-3 rounded">Assign Role</button>
    ${user.is_active
            ? `<button onclick="toggleUserSuspension('${user.id}', true)" class="bg-yellow-600 hover:bg-yellow-700 text-white text-sm font-bold py-1 px-3 rounded">Suspend</button>`
            : `<button onclick="toggleUserSuspension('${user.id}', false)" class="bg-green-600 hover:bg-green-700 text-white text-sm font-bold py-1 px-3 rounded">Unsuspend</button>`
        }
</td>
                </tr>
            `).join('');
    }

    function renderRoles(roles) {
        allRoles = roles; // Cache roles for modal
        roleList.innerHTML = roles.map(role => `
        <li>
            <a href="/admin/roles/${encodeURIComponent(role.name)}" class="block bg-gray-700 p-2 rounded hover:bg-gray-600 transition-colors">
                ${role.name} <span class="text-gray-400 text-sm">- Level ${role.level || 'N/A'}</span>
            </a>
        </li>
    `).join('');
        modalRoleSelect.innerHTML = roles.map(role => `<option value="${role.name}">${role.name}</option>`).join('');
    }


    // --- Event Handlers ---
    async function handleSearch() {
        try {
            const users = await apiRequest(`/users/search?identity=${userSearchInput.value}`);
            renderUsers(users);
        } catch (error) {
            showToast(error.message, true);
        }
    }

    async function handleCreateRole(e) {
        e.preventDefault();
        const name = document.getElementById('role-name').value;
        const description = document.getElementById('role-description').value;
        const level = document.getElementById('role-level').value;
        try {
            await apiRequest('/roles', 'POST', {name, description, level: level ? parseInt(level) : null});
            showToast(`Role '${name}' created successfully.`);
            createRoleForm.reset();
            fetchInitialData(); // Refresh roles list
        } catch (error) {
            showToast(error.message, true);
        }
    }

    async function toggleUserSuspension(userId, shouldSuspend) {
        const endpoint = shouldSuspend ? `/users/${userId}/suspend` : `/users/${userId}/unsuspend`;
        const action = shouldSuspend ? 'suspended' : 'unsuspended';
        try {
            await apiRequest(endpoint, 'POST', {reason: `Action from admin dashboard`});
            showToast(`User successfully ${action}.`);
            handleSearch(); // Refresh user list
        } catch (error) {
            showToast(error.message, true);
        }
    }

    function openAssignRoleModal(userId, username) {
        modalUserId.value = userId;
        modalUsername.textContent = username;
        modal.classList.add('active');
    }

    function closeModal() {
        modal.classList.remove('active');
    }

    async function submitAssignRole() {
        const userId = modalUserId.value;
        const roleName = modalRoleSelect.value;
        const scope = document.getElementById('modal-scope-input').value;
        try {
            await apiRequest('/users/roles/assign', 'POST', {user_id: userId, role_name: roleName, scope});
            showToast(`Role '${roleName}' assigned successfully.`);
            closeModal();
        } catch (error) {
            showToast(error.message, true);
        }
    }

    // --- Initialization ---
    async function fetchInitialData() {
        try {
            // Fetch roles first to populate the role-related UI elements
            const roles = await apiRequest('/roles'); // Assuming you'll create a GET /roles endpoint
            renderRoles(roles);

            // Then fetch users
            const users = await apiRequest('/users/search');
            renderUsers(users);
        } catch (error) {
            showToast(error.message, true);
        }
    }

    document.addEventListener('DOMContentLoaded', () => {
        userSearchInput.addEventListener('input', handleSearch);
        createRoleForm.addEventListener('submit', handleCreateRole);
        fetchInitialData();
        handleSearch();
    });
</script>
</body>
</html>