import {
  apiDelete,
  apiGet,
  apiPost,
  apiPut,
  isAuthRedirectError,
} from '../api.js';
import { guard } from '../core/auth-guard.js';
import {
  collectExtrasFromMachineForm,
  extrasTableHtml,
} from '../core/machine-extras.js';
import { extrasName } from '../core/utils.js';

const UUID =
  /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;

const loadingEl = document.getElementById('page-loading');
const badIdEl = document.getElementById('machine-bad-id');
const errEl = document.getElementById('page-error');
const mainEl = document.getElementById('page-main');
const panelView = document.getElementById('panel-machine-view');
const formM = document.getElementById('form-m');

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

function fillView(m) {
  document.getElementById('machine-title').textContent = m.name;
  document.getElementById('m-typ').textContent = m.typ;
  document.getElementById('m-serial').textContent = m.seriennummer;
  document.getElementById('m-standort').textContent = m.standort;
  const ort = extrasName(m);
  const row = document.getElementById('m-extras-name-row');
  if (ort) {
    row.hidden = false;
    document.getElementById('m-extras-name').textContent = ort;
  } else {
    row.hidden = true;
  }
  const tid = `/tickets.html?machineId=${encodeURIComponent(m.id)}`;
  document.getElementById('m-link-tickets').href = tid;
  document.getElementById('m-link-tickets-edit').href = tid;
  document.getElementById('machine-extras-view').innerHTML = extrasTableHtml(m.extras);
}

function fillEdit(m) {
  document.getElementById('input-m-name').value = m.name;
  document.getElementById('input-m-typ').value = m.typ;
  document.getElementById('input-m-serial').value = m.seriennummer;
  document.getElementById('input-m-standort').value = m.standort;
  document.getElementById('input-m-list-status').value = m.listStatus || '';
  document.getElementById('machine-extras-edit').innerHTML = extrasTableHtml(m.extras, {
    editable: true,
  });
}

function showViewMode() {
  panelView.hidden = false;
  formM.hidden = true;
}

function showEditMode() {
  panelView.hidden = true;
  formM.hidden = false;
}

async function viewMachineDetail(id, options = {}) {
  const { startInEditMode = false } = options;
  const m = await apiGet(`/machines/${id}`);

  fillView(m);
  if (startInEditMode) {
    fillEdit(m);
    showEditMode();
  } else {
    document.getElementById('machine-extras-edit').innerHTML = '';
    showViewMode();
  }

  document.getElementById('btn-m-del').onclick = async () => {
    if (!confirm('Maschine wirklich löschen?')) return;
    await apiDelete(`/machines/${id}`);
    location.href = '/machines.html';
  };

  document.getElementById('btn-m-edit').onclick = () => {
    fillEdit(m);
    showEditMode();
  };

  document.getElementById('btn-m-dup').onclick = async () => {
    const body = {
      name: `${m.name} (Kopie)`,
      typ: m.typ,
      seriennummer: `${m.seriennummer} - Kopie`,
      standort: m.standort,
      listStatus: m.listStatus || '',
    };
    if (m.extras && typeof m.extras === 'object') {
      body.extras = JSON.parse(JSON.stringify(m.extras));
    }
    try {
      const created = await apiPost('/machines', body);
      location.href = `/machine.html?id=${encodeURIComponent(created.id)}&edit=1`;
    } catch (err) {
      alert(err.message || 'Duplizieren fehlgeschlagen.');
    }
  };

  formM.onsubmit = async (e) => {
    e.preventDefault();
    const body = {
      name: formM.elements.name.value,
      typ: formM.elements.typ.value,
      seriennummer: formM.elements.seriennummer.value,
      standort: formM.elements.standort.value,
      listStatus: formM.elements.listStatus.value || '',
      extras: collectExtrasFromMachineForm(formM, m),
    };
    await apiPut(`/machines/${id}`, body);
    location.reload();
  };

  document.getElementById('m-cancel').onclick = () => {
    fillView(m);
    document.getElementById('machine-extras-edit').innerHTML = '';
    showViewMode();
  };

  document.getElementById('btn-m-del-edit').onclick = async () => {
    if (!confirm('Maschine wirklich löschen?')) return;
    await apiDelete(`/machines/${id}`);
    location.href = '/machines.html';
  };
}

async function init() {
  const st = await guard({ activeNav: 'machines' });
  if (!st) return;

  const params = new URLSearchParams(location.search);
  const id = params.get('id');
  const startInEditMode = params.get('edit') === '1';
  if (!id || !UUID.test(id)) {
    loadingEl.hidden = true;
    badIdEl.hidden = false;
    return;
  }

  loadingEl.hidden = true;
  mainEl.hidden = false;

  try {
    await viewMachineDetail(id, { startInEditMode });
    if (startInEditMode) {
      history.replaceState(null, '', `/machine.html?id=${encodeURIComponent(id)}`);
    }
  } catch (e) {
    if (isAuthRedirectError(e)) return;
    showError(e.message || 'Fehler');
  }
}

init();
