// /dashboard/panels/assignUsers.js

export async function render(container) {

  console.log('ASSIGN USERS PANEL RENDER CALLED');

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

    <div class="form-panel">

      <div class="form-group">
        <label>Select Project</label>
        <select id="projectSelect"></select>
      </div>

      <div class="form-group">
        <label>Select User</label>
        <select id="userSelect"></select>
      </div>

      <button id="assignBtn" class="btn-primary">Assign User</button>

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

    <hr>

    <h3>Assigned Users</h3>
    <ul id="assignedUsers"></ul>
  `;

  const token = localStorage.getItem('token');
  if (!token) return;

  const API = window.location.origin;

  const projectSelect = container.querySelector('#projectSelect');
  const userSelect = container.querySelector('#userSelect');
  const assignBtn = container.querySelector('#assignBtn');
  const msg = container.querySelector('#assignMsg');
  const assignedList = container.querySelector('#assignedUsers');

  /* ---------------- LOAD PROJECTS ---------------- */

  async function loadProjects() {

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

    const data = await res.json();

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

    projectSelect.innerHTML = '';

    projects.forEach(p => {
      const opt = document.createElement('option');
      opt.value = p.id;
      opt.textContent = p.name;
      projectSelect.appendChild(opt);
    });

    // auto-select from previous panel
    if (window.currentProjectId) {
      projectSelect.value = window.currentProjectId;
      loadAssignedUsers(window.currentProjectId);
    }
  }

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

  async function loadUsers() {

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

    const data = await res.json();

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

    userSelect.innerHTML = '';

    users.forEach(u => {

      const opt = document.createElement('option');
      opt.value = u.id;

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

      userSelect.appendChild(opt);
    });
  }

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

  async function loadAssignedUsers(projectId) {

    assignedList.innerHTML = '<li>Loading...</li>';

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

    const data = await res.json();

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

    assignedList.innerHTML = '';

    if (!users.length) {
      assignedList.innerHTML = '<li>No users assigned</li>';
      return;
    }

    users.forEach(u => {

      const li = document.createElement('li');

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

      const span = document.createElement('span');
      span.textContent = name;

      const removeBtn = document.createElement('button');
      removeBtn.textContent = 'Remove';

      removeBtn.onclick = async () => {

        await fetch(`${API}/projects/${projectId}/users/${u.id}`, {
          method: 'DELETE',
          headers: { Authorization: `Bearer ${token}` }
        });

        loadAssignedUsers(projectId);
      };

      li.appendChild(span);
      li.appendChild(removeBtn);
      assignedList.appendChild(li);
    });
  }

  /* ---------------- ASSIGN USER ---------------- */

  assignBtn.onclick = async () => {

    assignBtn.disabled = true;
    msg.textContent = 'Assigning...';

    const projectId = projectSelect.value;
    const userId = userSelect.value;

    const res = await fetch(`${API}/projects/${projectId}/users`, {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ userId })
    });

    const data = await res.json();

    assignBtn.disabled = false;

    if (!data.success) {
      msg.textContent = 'Assignment failed';
      return;
    }

    msg.textContent = 'User assigned';
    loadAssignedUsers(projectId);
  };

  projectSelect.onchange = () => {
    loadAssignedUsers(projectSelect.value);
  };

  /* ---------------- INIT ---------------- */

  await loadProjects();
  await loadUsers();
}
