// Check authentication
const auth = requireAuth();

if (!auth) {
	// Redirect handled by checkAdminAuth
} else {
	console.log("Authenticated admin:", auth);
	// Set admin info in header
	const user = getUserData();
	document.getElementById(
		"adminName"
	).textContent = `${user.first_name} ${user.last_name}`;
	document.getElementById(
		"adminAvatar"
	).textContent = `${user.first_name[0]}${user.last_name[0]}`;
}

let allUsers = [];

document.addEventListener("DOMContentLoaded", () => {
	loadUsers();
	loadDepartments();
	const user = getUserData();
	if (user) {
		document.getElementById(
			"adminName"
		).textContent = `${user.first_name} ${user.last_name}`;
		document.getElementById(
			"adminAvatar"
		).textContent = `${user.first_name[0]}${user.last_name[0]}`;
	}
	loadUserRoles(user.role);
});

async function loadDepartments() {
	try {
		const response = await apiRequest(API_ENDPOINTS.DEPARTMENTS_LIST);
		if (response && response.success) {
			const departments = response.data.departments;
			const departmentDropdown = document.getElementById("department");
			if (departmentDropdown) {
				departmentDropdown.innerHTML = `
          <option value="">Select Department</option>
          ${departments
						.map((dept) => `<option value="${dept.id}">${dept.name}</option>`)
						.join("")}
        `;
			}
		}
	} catch (error) {
		console.error("Error loading departments:", error);
	}
}

async function loadUserRoles(role) {
	try {
		const response = await apiRequest(
			`${API_ENDPOINTS.ROLES_LIST}?role=${encodeURIComponent(role)}`
		);
		if (response && response.success) {
			const roles = response.data.roles;
			const rolesDropdown = document.getElementById("role");
			if (rolesDropdown) {
				rolesDropdown.innerHTML = `
          <option value="">Select Role</option>
          ${roles
						.map(
							(role) => `<option value="${role.id}">${role.role_name}</option>`
						)
						.join("")}
        `;
			}
		}
	} catch (error) {
		console.error("Error loading user roles:", error);
	}
}

async function loadUsers() {
	try {
		const response = await apiRequest(API_ENDPOINTS.USERS_LIST);

		if (response && response.success) {
			allUsers = response.data.users;
			displayUsers(allUsers);
		}
	} catch (error) {
		console.error("Error loading users:", error);
		document.getElementById("usersTableBody").innerHTML = `
      <tr>
          <td colspan="7" style="text-align: center; padding: 40px; color: #ef4444;">
              Error loading users
          </td>
      </tr>
    `;
	}
}

function displayUsers(users) {
	const tbody = document.getElementById("usersTableBody");

	if (users.length === 0) {
		tbody.innerHTML = `
      <tr>
          <td colspan="8" style="text-align: center; padding: 40px; color: #888;">
              No users found
          </td>
      </tr>
    `;
		return;
	}

	tbody.innerHTML = users
		.map(
			(user) => `
        <tr>
            <td>
                <div style="display: flex; align-items: center; gap: 10px;">
                    <img src="${
											user.avatar_url || "../../public/diverse-user-avatars.png"
										}" alt="${
				user.first_name
			}" style="width: 40px; height: 40px; border-radius: 50%; object-fit: cover;">
                    <span>${user.first_name} ${user.last_name}</span>
                </div>
            </td>
            <td>${user.gender}</td>
            <td>${user.email}</td>
            <td>${user.phone_number || "N/A"}</td>
            <td>${user.department_name || "N/A"}</td>
            <td><span class="badge ${getRoleBadgeClass(user.role)}">${
				user.role_name
			}</span></td>
            <td><span class="badge ${
							user.is_verified ? "success" : "warning"
						}">${user.is_verified ? "Verified" : "Pending"}</span></td>
            <td>
                <div class="action-buttons">
                    <button class="btn-icon" onclick="editUser(${
											user.id
										})" title="Edit">
                        <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path>
                        </svg>
                    </button>
                    <button class="btn-icon danger" onclick="deleteUser(${
											user.id
										}, '${user.first_name} ${user.last_name}')" title="Delete">
                        <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                        </svg>
                    </button>
                </div>
            </td>
        </tr>
    `
		)
		.join("");
}

function getRoleBadgeClass(role) {
	const classes = {
		admin: "danger",
		worker: "primary",
		delegate: "info",
		user: "success",
	};
	return classes[role] || "info";
}

// Search and filter
document.getElementById("searchInput").addEventListener("input", filterUsers);
document.getElementById("roleFilter").addEventListener("change", filterUsers);

function filterUsers() {
	const searchTerm = document.getElementById("searchInput").value.toLowerCase();
	const roleFilter = document.getElementById("roleFilter").value;

	let filtered = allUsers;

	if (searchTerm) {
		filtered = filtered.filter(
			(user) =>
				user.first_name.toLowerCase().includes(searchTerm) ||
				user.last_name.toLowerCase().includes(searchTerm) ||
				user.email.toLowerCase().includes(searchTerm)
		);
	}

	if (roleFilter) {
		filtered = filtered.filter((user) => user.role === roleFilter);
	}

	displayUsers(filtered);
}

// Modal functions
function openCreateUserModal() {
	document.getElementById("modalTitle").textContent = "Add New User";
	document.getElementById("userForm").reset();
	document.getElementById("userId").value = "";
	// document.getElementById("passwordGroup").style.display = "block"
	// document.getElementById("password").required = true
	document.getElementById("userModal").style.display = "flex";
}

function editUser(userId) {
	const user = allUsers.find((u) => u.id === userId);
	if (!user) return;

	document.getElementById("modalTitle").textContent = "Edit User";
	document.getElementById("userId").value = user.id;
	document.getElementById("firstName").value = user.first_name;
	document.getElementById("lastName").value = user.last_name;
	document.getElementById("email").value = user.email;
	document.getElementById("phone").value = user.phone_number || "";
	document.getElementById("gender").value = user.gender || "";
	document.getElementById("department").value = user.department_id || "";
	document.getElementById("role").value = user.role_id || "";
	document.getElementById("isHod").value = user.is_hod ? "1" : "0";
	// document.getElementById("userImage").value = user.profile_image || "";
	// document.getElementById("previewImg").src =
	// 	user.profile_image || "/diverse-user-avatars.png";
	// document.getElementById("imagePreview").style.display = user.profile_image
	// 	? "block"
	// 	: "none";
	document.getElementById("userModal").style.display = "flex";
}

function closeUserModal() {
	document.getElementById("userModal").style.display = "none";
}

async function saveUser() {
	const userId = document.getElementById("userId").value;
	// const imageFile = document.getElementById("userImage").files[0];

	const userData = {
		first_name: document.getElementById("firstName").value,
		last_name: document.getElementById("lastName").value,
		email: document.getElementById("email").value,
		phone_number: document.getElementById("phone").value,
		gender: document.getElementById("gender").value,
		department: document.getElementById("department").value,
		role: document.getElementById("role").value,
		is_hod: document.getElementById("isHod").value,
	};

	try {
		let response;

		const endpoint = userId
			? `${API_ENDPOINTS.USER_UPDATE}?id=${userId}`
			: `${API_ENDPOINTS.USER_CREATE}`;
		const method = userId ? "PUT" : "POST";

		response = await apiRequest(endpoint, {
			method,
			headers: getAuthHeaders(),
			body: JSON.stringify(userData),
		});

		if (response && response.success) {
			closeUserModal();
			loadUsers();
			showMessage(
				userId ? "User updated successfully" : "User created successfully",
				"success"
			);
		} else {
			showMessage(response.message || "Failed to save user", "error");
		}
	} catch (error) {
		console.error("Error saving user:", error);
		showMessage("An error occurred while saving the user", "error");
	}
}

async function saveUser() {
	const userId = document.getElementById("userId").value;
	const userData = {
		first_name: document.getElementById("firstName").value,
		last_name: document.getElementById("lastName").value,
		email: document.getElementById("email").value,
		phone_number: document.getElementById("phone").value,
		gender: document.getElementById("gender").value,
		department: document.getElementById("department").value,
		role: document.getElementById("role").value,
		is_hod: document.getElementById("isHod").value,
	};

	try {
		const endpoint = userId
			? `${API_ENDPOINTS.USER_UPDATE}?id=${userId}`
			: `${API_ENDPOINTS.USER_CREATE}`;
		const method = userId ? "PUT" : "POST";

		const data = await apiRequest(endpoint, {
			method,
			body: JSON.stringify(userData),
		});

		if (data && data.success) {
			closeUserModal();
			loadUsers();
			showMessage(
				userId ? "User updated successfully" : "User created successfully",
				"success"
			);
		} else {
			showMessage(data.message || "Failed to save user", "error");
		}
	} catch (error) {
		console.error("Error saving user:", error);
		showMessage("An error occurred while saving the user", "error");
	}
}

async function deleteUser(userId, userName) {
	if (!confirm(`Are you sure you want to delete ${userName}?`)) return;

	try {
		const data = await apiRequest(`${API_ENDPOINTS.USER_DELETE}?id=${userId}`, {
			method: "DELETE",
		});

		if (data && data.success) {
			loadUsers();
			showMessage("User deleted successfully", "success");
		} else {
			showMessage(data.message || "Failed to delete user", "error");
		}
	} catch (error) {
		console.error("Error deleting user:", error);
		showMessage("An error occurred while deleting the user", "error");
	}
}

function toggleSidebar() {
	document.getElementById("adminSidebar").classList.toggle("open");
}

function previewImage(event) {
	const file = event.target.files[0];
	if (file) {
		const reader = new FileReader();
		reader.onload = (e) => {
			const preview = document.getElementById("imagePreview");
			const previewImg = document.getElementById("previewImg");
			previewImg.src = e.target.result;
			preview.style.display = "block";
		};
		reader.readAsDataURL(file);
	}
}

function removeImage() {
	document.getElementById("userImage").value = "";
	document.getElementById("imagePreview").style.display = "none";
}
