if (isAuthenticated()) {
	window.location.href = "index.html";
}

let registrationEmail = "";

function setButtonLoading(buttonId, isLoading, originalText = "Continue") {
	const button = document.getElementById(buttonId);
	if (!button) return;

	if (isLoading) {
		button.disabled = true;
		button.innerHTML =
			'<span style="display: inline-block; margin-right: 8px;">⏳</span>Processing...';
		button.style.opacity = "0.7";
	} else {
		button.disabled = false;
		button.innerHTML = originalText;
		button.style.opacity = "1";
	}
}

async function apiLocalRequest(endpoint, options) {
	// Placeholder for API request function
	const response = await fetch(endpoint, options);
	const responseData = await response.json();

	if (!response.ok) {
		throw new Error(
			responseData.message || "An error occurred while processing the request."
		);
	}

	return responseData;
}

// Step 1: Email submission
document.getElementById("emailForm").addEventListener("submit", async (e) => {
	e.preventDefault();

	const email = document.getElementById("email").value;
	registrationEmail = email;

	setButtonLoading("registerBtn", true);

	let response;
	try {
		response = await apiLocalRequest(API_ENDPOINTS.REGISTER, {
			method: "POST",
			body: JSON.stringify({ email }),
		});

		if (response.success) {
			if (response.data.user_id) {
				document.getElementById("emailForm").classList.add("hidden");
				document.getElementById("otpForm").classList.add("hidden");
				document.getElementById("completeForm").classList.remove("hidden");
				await fetchUserRolesAndDepartments();
			} else {
				// Show OTP form
				document.getElementById("emailForm").classList.add("hidden");
				document.getElementById("otpForm").classList.remove("hidden");

				showMessage("Verification code sent to your email", "success");

				// Focus first OTP input
				document.getElementById("otp1").focus();
			}
		} else {
			showMessage(response.message, "error");
		}
	} catch (error) {
		showMessage(
			error.message ||
				"Registration failed! You might have uncompleted registration. Kindly contact Admin for support.",
			"error"
		);
	} finally {
		setButtonLoading("registerBtn", false, "Continue");
	}
});

// fetch user roles and populate
async function fetchUserRolesAndDepartments() {
	const response = await apiLocalRequest(API_ENDPOINTS.REGISTRATION_DATA_LIST);

	if (response && response.data.roles.length > 0) {
		// populate the roles dropdown
		const rolesDropdown = document.getElementById("userRole");
		rolesDropdown.innerHTML = '<option value="">Select your role</option>';

		response.data.roles.forEach((role) => {
			const option = document.createElement("option");
			option.value = role.id;
			option.textContent = role.role_name;
			rolesDropdown.appendChild(option);
		});
	}

	if (response && response.data.departments.length > 0) {
		// populate the roles dropdown
		const departmentsDropdown = document.getElementById("department");
		departmentsDropdown.innerHTML =
			'<option value="">Select your department</option>';

		response.data.departments.forEach((department) => {
			const option = document.createElement("option");
			option.value = department.id;
			option.textContent = department.name;
			departmentsDropdown.appendChild(option);
		});
	}
}

// OTP input handling
const otpInputs = document.querySelectorAll(".otp-input");
otpInputs.forEach((input, index) => {
	input.addEventListener("input", (e) => {
		if (e.target.value.length === 1 && index < otpInputs.length - 1) {
			otpInputs[index + 1].focus();
		}
	});

	input.addEventListener("keydown", (e) => {
		if (e.key === "Backspace" && e.target.value === "" && index > 0) {
			otpInputs[index - 1].focus();
		}
	});
});

const otpPaste = document.getElementById("otpPaste");
if (otpPaste) {
	otpPaste.addEventListener("paste", (e) => {
		const pastedText = e.clipboardData
			.getData("text")
			.replace(/\D/g, "")
			.slice(0, 6);

		if (pastedText.length === 6) {
			for (let i = 0; i < 6; i++) {
				otpInputs[i].value = pastedText[i];
			}
			otpInputs[5].focus();
		}
	});

	// Allow clicking anywhere on OTP container to focus paste input
	document.querySelector(".otp-container").addEventListener("click", () => {
		otpPaste.focus();
	});
}

// Step 2: OTP verification
async function verifyOTP() {
	const otp = Array.from(otpInputs)
		.map((input) => input.value)
		.join("");

	if (otp.length !== 6) {
		showMessage("Please enter all 6 digits", "error");
		return;
	}

	setButtonLoading("verifyBtn", true, "Verify");

	try {
		await apiRequest(API_ENDPOINTS.VERIFY, {
			method: "POST",
			body: JSON.stringify({
				email: registrationEmail,
				otp,
			}),
		});

		// Show success message
		showMessage("Verification successful", "success");

		// Show complete registration form
		setTimeout(async () => {
			document.getElementById("otpForm").classList.add("hidden");
			document.getElementById("completeForm").classList.remove("hidden");
			await fetchUserRolesAndDepartments();
		}, 1500);
	} catch (error) {
		showMessage(error.message || "Verification failed", "error");
		setButtonLoading("verifyBtn", false, "Verify");
	}
}

// Step 3: Complete registration
document
	.getElementById("completeForm")
	.addEventListener("submit", async (e) => {
		e.preventDefault();

		const firstName = document.getElementById("firstName").value;
		const lastName = document.getElementById("lastName").value;
		const phoneNumber = document.getElementById("phoneNumber").value;
		const gender = document.getElementById("gender").value;
		const department = document.getElementById("department").value;
		const userRole = document.getElementById("userRole").value;
		const password = document.getElementById("password").value;
		const confirmPassword = document.getElementById("confirmPassword").value;

		if (password !== confirmPassword) {
			showMessage("Passwords do not match", "error");
			return;
		}

		setButtonLoading("completeBtn", true, "Continue");

		let response;
		try {
			response = await apiRequest(API_ENDPOINTS.COMPLETE_REGISTRATION, {
				method: "POST",
				body: JSON.stringify({
					email: registrationEmail,
					first_name: firstName,
					last_name: lastName,
					phone_number: phoneNumber,
					gender,
					department,
					role: userRole,
					password,
				}),
			});

			// Save token and user data
			setAuthToken(response.data.token);
			setUserData(response.data.user);

			showMessage("Registration completed successfully", "success");

			// Redirect to home
			setTimeout(() => {
				window.location.href = "index.html";
			}, 1500);
		} catch (error) {
			showMessage(error.message || "Registration completion failed", "error");
			setButtonLoading("completeBtn", false, "Continue");
		}
	});
