import { apiGet, apiPost, isAuthRedirectError } from '../api.js';
import { machineListStatusRowClass } from '../core/constants.js';
import { guard } from '../core/auth-guard.js';
import { esc } from '../core/utils.js';

function rowClassForListStatus(listStatus) {
  const code =
    listStatus && machineListStatusRowClass[listStatus] !== undefined
      ? listStatus
      : '';
  return machineListStatusRowClass[code];
}

const loadingEl = document.getElementById('page-loading');
const mainEl = document.getElementById('page-main');
const errEl = document.getElementById('page-error');

function showError(msg) {
  loadingEl.hidden = true;
  mainEl.hidden = true;
  errEl.hidden = false;
  errEl.textContent = msg;
}

function renderRows(machines) {
  const tbody = document.getElementById('machine-table-body');
  tbody.innerHTML = machines
    .map((m) => {
      const x = m.extras || {};
      const rc = rowClassForListStatus(m.listStatus);
      return `<tr class="${esc(rc)}">
                <td><a href="/machine.html?id=${esc(m.id)}">${esc(m.seriennummer)}</a></td>
                <td>${esc(m.typ)}</td>
                <td>${esc(x.Konzern || '')}</td>
                <td>${esc(x.Name || '')}</td>
                <td>${esc(x.Stadt || '')}</td>
                <td>${esc(x.Land || '')}</td>
                <td>${esc(x.Jahr || '')}</td>
              </tr>`;
    })
    .join('');
}

function initNewMachineCollapse() {
  const body = document.getElementById('new-machine-section-body');
  const toggle = document.getElementById('new-machine-toggle');
  const chev = toggle.querySelector('.ldap-chevron');
  function setOpen(open) {
    body.hidden = !open;
    toggle.setAttribute('aria-expanded', String(open));
    chev.textContent = open ? '▲' : '▼';
  }
  toggle.onclick = () => setOpen(body.hidden);
}

async function run() {
  const machines = await apiGet('/machines');
  document.getElementById('machine-count').textContent = String(machines.length);
  renderRows(machines);

  initNewMachineCollapse();

  const formNew = document.getElementById('form-new-machine');
  formNew.addEventListener('submit', async (e) => {
    e.preventDefault();
    const fd = new FormData(formNew);
    const btn = formNew.querySelector('button[type="submit"]');
    btn.disabled = true;
    try {
      const body = Object.fromEntries(fd.entries());
      const created = await apiPost('/machines', {
        name: body.name,
        typ: body.typ,
        seriennummer: body.seriennummer,
        standort: body.standort,
        listStatus: body.listStatus || '',
      });
      location.href = `/machine.html?id=${encodeURIComponent(created.id)}`;
    } catch (err) {
      alert(err.message || 'Anlegen fehlgeschlagen.');
      btn.disabled = false;
    }
  });

  const inp = document.getElementById('machine-filter');
  const tbody = document.getElementById('machine-table-body');
  inp.addEventListener('input', () => {
    const q = inp.value.toLowerCase().trim();
    tbody.querySelectorAll('tr').forEach((tr) => {
      tr.hidden = !!(q && !tr.textContent.toLowerCase().includes(q));
    });
  });
}

async function init() {
  const st = await guard({ activeNav: 'machines' });
  if (!st) return;
  loadingEl.hidden = true;
  mainEl.hidden = false;
  try {
    await run();
  } catch (e) {
    if (isAuthRedirectError(e)) return;
    showError(e.message || 'Fehler');
  }
}

init();
