// /dashboard/panels/userList.js

export async function render(container) {

    window.addEventListener('user-online', e => {
        updateUserDot(e.detail, true);
    });

    window.addEventListener('user-offline', e => {
        updateUserDot(e.detail, false);
    });


    container.innerHTML = `
    <div class="panel-header">
      <h2>Organization Users</h2>
    </div>

    <div id="usersMsg" class="form-message"></div>

    <table class="data-table">
      <thead>
        <tr>
          <th>Name</th>
          <th>Email</th>
          <th>Role</th>
          <th>Status</th>
          <th>Last Login</th>
          <th>Actions</th>
        </tr>
      </thead>
      <tbody id="usersBody"></tbody>
    </table>
  `;

    const msg = container.querySelector('#usersMsg');
    const tbody = container.querySelector('#usersBody');

    const token = localStorage.getItem('token');
    if (!token) {
        msg.textContent = 'Not authenticated';
        return;
    }

    const API = window.location.origin;

    /* ---------------------------
        LOAD USERS
    ---------------------------- */

    async function loadUsers() {

        msg.textContent = 'Loading users...';
        tbody.innerHTML = '';

        try {

            const res = await fetch(`${API}/users`, {
                headers: { Authorization: `Bearer ${token}` }
            });

            const data = await res.json();

            console.log('USER LIST RESPONSE:', data);

            const users = Array.isArray(data)
                ? data
                : data.users || data.data || [];

            if (!users.length) {
                msg.textContent = 'No users found';
                return;
            }

            msg.textContent = '';

            users.forEach(u => {

                const tr = document.createElement('tr');
                tr.dataset.userId = u.id;
                const onlineDot = u.is_online
  ? '<span class="dot online"></span>'
  : '<span class="dot offline"></span>';


                const fullName =
                    `${u.firstName || ''} ${u.lastName || ''}`.trim() ||
                    u.fullName ||
                    `User ${u.id}`;

                let roleUI = '';

                if (window.currentUserRole === 'owner' && u.role !== 'owner') {

                    roleUI = `
    <select class="role-select" data-id="${u.id}">
      <option value="admin" ${u.role === 'admin' ? 'selected' : ''}>Admin</option>
      <option value="member" ${u.role === 'member' ? 'selected' : ''}>Member</option>
    </select>
  `;

                } else {

                    roleUI = `
    <span class="role-badge role-${u.role}">
      ${u.role}
    </span>
  `;
                }


                const statusBadge = u.isActive
                    ? `<span class="status active">Active</span>`
                    : `<span class="status inactive">Disabled</span>`;

                const lastLogin = u.last_seen
                    ? new Date(u.last_seen).toLocaleString()
                    : 'Never';


                tr.innerHTML = `
          <td>${onlineDot} ${fullName}</td>
          <td>${u.email || '—'}</td>
          <td>${roleUI}</td>
          <td>${statusBadge}</td>
          <td>${lastLogin}</td>
          <td class="action-col">
            <button class="icon-btn disable-btn" title="Enable/Disable">
              ${u.isActive ? '🚫' : '✅'}
            </button>
            <button class="icon-btn reset-btn" title="Reset Password">
              🔑
            </button>
          </td>
        `;

                /* -------- Disable / Enable User -------- */

                tr.querySelector('.disable-btn').onclick = async () => {

                    const action = u.isActive ? 'disable' : 'enable';

                    if (!confirm(`Are you sure you want to ${action} this user?`)) {
                        return;
                    }

                    await fetch(`${API}/users/${u.id}/status`, {
                        method: 'PATCH',
                        headers: {
                            Authorization: `Bearer ${token}`,
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            isActive: u.isActive ? 0 : 1
                        })
                    });

                    loadUsers();
                };

                /* -------- Reset Password -------- */

                tr.querySelector('.reset-btn').onclick = async () => {

                    if (!confirm('Reset password for this user?')) return;

                    const res = await fetch(`${API}/users/${u.id}/reset-password`, {
                        method: 'POST',
                        headers: { Authorization: `Bearer ${token}` }
                    });

                    const result = await res.json();

                    if (result.success) {
                        alert('Temporary password sent to user email');
                    } else {
                        alert('Password reset failed');
                    }
                };

                tbody.appendChild(tr);
                const roleSelect = tr.querySelector('.role-select');

                if (roleSelect) {

                    roleSelect.onchange = async () => {

                        const newRole = roleSelect.value;
                        const userId = roleSelect.dataset.id;

                        if (!confirm('Change user role?')) {
                            loadUsers();
                            return;
                        }

                        await fetch(`${API}/users/${userId}/role`, {
                            method: 'PATCH',
                            headers: {
                                Authorization: `Bearer ${token}`,
                                'Content-Type': 'application/json'
                            },

                            body: JSON.stringify({ role: newRole })
                        });

                        loadUsers();
                    };
                }

            });

        } catch (err) {
            console.error(err);
            msg.textContent = 'Failed to load users';
        }
    }


    /* ---------------------------
        INIT
    ---------------------------- */
    function updateUserDot(userId, isOnline) {

        const row = document.querySelector(`[data-user-id="${userId}"]`);

        if (!row) return;

        const dot = row.querySelector('.dot');

        if (!dot) return;

        dot.className = isOnline ? 'dot online' : 'dot offline';
    }

    loadUsers();
}
