const form = document.getElementById("api-key-form");
const alertBox = document.getElementById("api-key-alert");
const secretPanel = document.getElementById("api-key-secret-panel");
const secretInput = document.getElementById("api-key-secret");
const tableBody = document.querySelector("#api-key-table tbody");

function showAlert(message, kind) {
	if (!alertBox) {
		return;
	}
	alertBox.textContent = message;
	alertBox.className = `alert alert-${kind}`;
}

function detailMessage(payload) {
	if (payload && typeof payload.detail === "string") {
		return payload.detail;
	}
	return "Request failed";
}

function appendKeyRow(key) {
	const empty = document.getElementById("api-key-empty");
	if (empty) {
		empty.remove();
	}
	if (!tableBody) {
		return;
	}
	const row = document.createElement("tr");
	row.dataset.keyId = key.id;
	const cells = [key.id, key.readonly ? "Read only" : "Read and write", key.time_issued, key.time_expiry || "Never"];
	for (const text of cells) {
		const cell = document.createElement("td");
		cell.textContent = text;
		row.append(cell);
	}
	const action = document.createElement("td");
	action.className = "text-end";
	const button = document.createElement("button");
	button.type = "button";
	button.className = "btn btn-outline-danger btn-sm";
	button.dataset.revokeKey = key.id;
	button.textContent = "Revoke";
	button.addEventListener("click", () => {
		revokeKey(key.id);
	});
	action.append(button);
	row.append(action);
	tableBody.append(row);
}

async function revokeKey(keyId) {
	const response = await fetch(`/user/keys?id=${encodeURIComponent(keyId)}`, {
		method: "DELETE",
		credentials: "same-origin",
	});
	if (!response.ok) {
		const payload = await response.json().catch(() => null);
		showAlert(detailMessage(payload), "danger");
		return;
	}
	const row = tableBody?.querySelector(`tr[data-key-id="${CSS.escape(keyId)}"]`);
	row?.remove();
	showAlert(`Revoked ${keyId}.`, "success");
	window.location.reload();
}

if (form) {
	form.addEventListener("submit", async (event) => {
		event.preventDefault();
		const idInput = document.getElementById("api-key-id");
		const readonlyInput = document.getElementById("api-key-readonly");
		const keyId = idInput instanceof HTMLInputElement ? idInput.value.trim() : "";
		const readonly = readonlyInput instanceof HTMLInputElement && readonlyInput.checked;
		const response = await fetch("/user/keys", {
			method: "POST",
			credentials: "same-origin",
			headers: { "Content-Type": "application/json" },
			body: JSON.stringify({ id: keyId, readonly }),
		});
		const payload = await response.json().catch(() => null);
		if (!response.ok) {
			showAlert(detailMessage(payload), "danger");
			return;
		}
		if (secretPanel && secretInput instanceof HTMLInputElement) {
			secretInput.value = payload.secret;
			secretPanel.classList.remove("d-none");
		}
		appendKeyRow(payload);
		form.reset();
		showAlert("API key created.", "success");
		const max = Number(document.getElementById("api-key-table")?.dataset.apiKeyMax || "0");
		const held = tableBody ? tableBody.querySelectorAll("tr[data-key-id]").length : 0;
		if (max > 0 && held >= max) {
			form.remove();
		}
	});
}

document.querySelectorAll("[data-revoke-key]").forEach((button) => {
	button.addEventListener("click", () => {
		const keyId = button.getAttribute("data-revoke-key");
		if (keyId) {
			revokeKey(keyId);
		}
	});
});