from __future__ import annotations

from fastapi import FastAPI
from fastapi.responses import HTMLResponse

from ..layout.page import page


def register(app: FastAPI) -> None:
    @app.get("/ui/admin")
    async def ui_admin() -> HTMLResponse:
        body = """
<h1>Admin</h1>
<div class="card">
  <div class="muted">
    This page requires the <code>admin</code> token (set it in <a href="/ui/login">Login</a>).
  </div>
  <div style="height:14px"></div>

  <h3>Create user</h3>
  <div class="row">
    <input id="new-user-id" placeholder="user_id (e.g. alice)" style="max-width:320px" />
    <input id="new-display-name" placeholder="display_name (optional)" style="max-width:320px" />
    <button class="btn" id="create-user">Create</button>
  </div>
  <div style="height:10px"></div>
  <pre id="create-msg" class="muted"></pre>

  <div style="height:14px"></div>
  <div class="row">
    <button class="btn" id="refresh">Refresh</button>
  </div>
  <div style="height:10px"></div>
  <div id="out" class="muted">Loading...</div>
</div>
""".strip()
        script = """
const out = document.getElementById("out");
const createMsg = document.getElementById("create-msg");
const userIdEl = document.getElementById("new-user-id");
const displayNameEl = document.getElementById("new-display-name");

function esc(s) {
  s = String(s || "");
  return s.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;");
}

async function refresh() {
  out.textContent = "Loading...";
  try {
    const obj = await apiJson("/api/v2/users?limit=200");
    const users = (obj.users || []);
    function row(u) {
      const uid = u.user_id;
      const tok = u.token || "";
      const tokShort = tok ? (tok.length > 18 ? (tok.slice(0, 18) + "…") : tok) : "";
      const created = u.created_at || "";
      const updated = u.updated_at || "";
      const tCreated = u.token_created_at || "";
      const tUsed = u.token_last_used_at || "";
      return `<tr>
        <td><code>${esc(uid)}</code></td>
        <td class="muted">${esc(created)}</td>
        <td class="muted">${esc(updated)}</td>
        <td>
          <div class="row" style="gap:8px">
            <code title="${esc(tok)}">${esc(tokShort)}</code>
            <button class="btn" data-copy="${esc(tok)}">Copy</button>
            <button class="btn" data-issue="${esc(uid)}">Issue token</button>
          </div>
          <div class="muted" style="margin-top:6px">token_created_at: ${esc(tCreated)}; last_used_at: ${esc(tUsed)}</div>
        </td>
      </tr>`;
    }
    out.innerHTML = `
      <table>
        <thead><tr><th>User</th><th>Created</th><th>Updated</th><th>Token</th></tr></thead>
        <tbody>${users.map(row).join("") || "<tr><td colspan=4 class=muted>(none)</td></tr>"}</tbody>
      </table>
    `;
    for (const btn of out.querySelectorAll("button[data-copy]")) {
      btn.onclick = async () => { await copyText(btn.getAttribute("data-copy") || ""); };
    }
    for (const btn of out.querySelectorAll("button[data-issue]")) {
      btn.onclick = async () => {
        const uid = btn.getAttribute("data-issue");
        if (!uid) return;
        try {
          const r = await apiJson("/api/v2/users/" + encodeURIComponent(uid) + "/tokens", { method: "POST" });
          createMsg.textContent = "Issued token:\\n" + fmtJson(r);
          await refresh();
        } catch (e) {
          createMsg.textContent = "Error issuing token: " + (e.status || "") + "\\n" + (e.body || String(e));
        }
      };
    }
  } catch (e) {
    out.textContent = "Error: " + (e.status || "") + "\\n" + (e.body || String(e));
  }
}

document.getElementById("refresh").onclick = refresh;
document.getElementById("create-user").onclick = async () => {
  createMsg.textContent = "Creating...";
  const user_id = (userIdEl.value || "").trim();
  const display_name = (displayNameEl.value || "").trim();
  if (!user_id) { createMsg.textContent = "user_id is required"; return; }
  const payload = { user_id: user_id };
  if (display_name) payload.display_name = display_name;
  try {
    const r = await apiJson("/api/v2/users", { method: "POST", headers: {"Content-Type":"application/json"}, body: JSON.stringify(payload) });
    createMsg.textContent = "Created:\\n" + fmtJson(r);
    userIdEl.value = "";
    displayNameEl.value = "";
    await refresh();
  } catch (e) {
    createMsg.textContent = "Error: " + (e.status || "") + "\\n" + (e.body || String(e));
  }
};

refresh();
""".strip()
        return HTMLResponse(content=page("Admin", "admin", body, script))

