// 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 allDepartments = [];
let filteredDepartments = [];

// Load departments on page load
document.addEventListener("DOMContentLoaded", () => {
	loadDepartments();
});

async function loadDepartments() {
	try {
		const response = await apiRequest(API_ENDPOINTS.DEPARTMENTS_LIST);
		if (response.success) {
			allDepartments = response.data.departments;
			filteredDepartments = allDepartments;
			renderDepartments();
		} else {
			showMessage(response.message || "Failed to load departments", "error");
		}
	} catch (error) {
		console.error("Error loading departments:", error);
		showMessage("An error occurred while loading departments", "error");
	}
}

function renderDepartments() {
	const tbody = document.getElementById("departmentsTableBody");

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

	tbody.innerHTML = filteredDepartments
		.map(
			(dept) => `
		<tr>
			<td><strong>${dept.name}</strong></td>
			<td>${dept.description || "-"}</td>
			<td>${dept.member_count || 0}</td>
			<td>
				<span class="badge ${dept.is_active ? "success" : "warning"}">
					${dept.is_active ? "Active" : "Archived"}
				</span>
			</td>
			<td>${formatDate(dept.created_at)}</td>
			<td>
				<div class="action-buttons">
                    <button class="btn-icon" onclick="viewUsersInDepartment(${
											dept.id
										})" title="View Users">
                        <svg width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path>
                        </svg>
                    </button>
					<button class="btn-icon" onclick="editDepartment(${dept.id})" title="Edit">
						<svg width="18" height="18" 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>
					${
						dept.is_active
							? `
						<button class="btn-icon warning" onclick="archiveDepartment(${dept.id})" title="Archive">
							<svg width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24">
								<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 8h14M5 8a2 2 0 110-4h14a2 2 0 110 4M5 8v10a2 2 0 002 2h10a2 2 0 002-2V8m-9 4h4"></path>
							</svg>
						</button>
					`
							: `
						<button class="btn-icon success" onclick="restoreDepartment(${dept.id})" title="Restore">
							<svg width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24">
								<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
							</svg>
						</button>
					`
					}
					<button class="btn-icon danger" onclick="deleteDepartment(${
						dept.id
					})" title="Delete">
						<svg width="18" height="18" 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 searchDepartments() {
	const searchTerm = document.getElementById("searchInput").value.toLowerCase();
	const statusFilter = document.getElementById("statusFilter").value;

	filteredDepartments = allDepartments.filter((dept) => {
		const matchesSearch =
			dept.name.toLowerCase().includes(searchTerm) ||
			(dept.description && dept.description.toLowerCase().includes(searchTerm));

		const matchesStatus =
			statusFilter === "all" || dept.is_active === statusFilter;

		return matchesSearch && matchesStatus;
	});

	renderDepartments();
}

function filterDepartments() {
	searchDepartments();
}

function openCreateModal() {
	document.getElementById("modalTitle").textContent = "Add Department";
	document.getElementById("departmentForm").reset();
	document.getElementById("departmentId").value = "";
	document.getElementById("departmentModal").classList.remove("hidden");
	document.getElementById("departmentModal").style.display = "flex";
}

function editDepartment(id) {
	const department = allDepartments.find((d) => d.id === id);
	if (!department) return;

	document.getElementById("modalTitle").textContent = "Edit Department";
	// document.getElementById("submitBtnText").textContent = "Update Department";
	document.getElementById("departmentId").value = department.id;
	document.getElementById("departmentName").value = department.name;
	document.getElementById("departmentDescription").value =
		department.description || "";
	document.getElementById("departmentModal").classList.remove("hidden");
	document.getElementById("departmentModal").style.display = "flex";
}

function closeModal() {
	document.getElementById("departmentModal").style.display = "none";
	document.getElementById("departmentForm").reset();
}

document
	.getElementById("departmentForm")
	.addEventListener("submit", async (e) => {
		e.preventDefault();

		const departmentId = document.getElementById("departmentId").value;
		const name = document.getElementById("departmentName").value;
		const description = document.getElementById("departmentDescription").value;

		// const submitBtn = e.target.querySelector('button[type="submit"]');
		const submitSpinner = document.getElementById("submitSpinner");

		submitSpinner.style.display = "block";

		try {
			const body = departmentId
				? { id: departmentId, name, description }
				: { name, description };

			const response = await fetch(API_ENDPOINTS.DEPARTMENTS_LIST, {
				method: "POST",
				headers: getAuthHeaders(),
				body: JSON.stringify(body),
			});

			const result = await response.json();

			if (result.success) {
				showMessage(
					departmentId
						? "Department updated successfully"
						: "Department created successfully",
					"success"
				);
				closeModal();
				loadDepartments();
			} else {
				showMessage(result.message || "Operation failed", "error");
			}
		} catch (error) {
			console.error("Error saving department:", error);
			showMessage("An error occurred while saving the department", "error");
		} finally {
			submitSpinner.style.display = "none";
		}
	});

async function viewUsersInDepartment(id) {
	// check if the total users in the department exceed 0
	const department = allDepartments.find((d) => d.id === id);
	if (!department || department.member_count === 0) {
		showMessage("No users in this department", "info");
		return;
	}

	try {
		const response = await apiRequest(
			`${API_ENDPOINTS.USERS_LIST}?department_id=${id}`
		);
		if (response.success) {
			const users = response.data.users;
			document.getElementById(
				"usersInDeptTitle"
			).textContent = `Users in ${department.name} Department`;

			document.getElementById("usersInDeptTableBody").innerHTML = users
				.map(
					(user, index) => `
                    <tr>
                        <td>${index++}</td>
                        <td>${user.first_name} ${user.last_name}</td>
                        <td>${user.phone_number}</td>
                    </tr>
                `
				)
				.join("");
			document.getElementById("usersInDeptModal").classList.remove("hidden");
			document.getElementById("usersInDeptModal").style.display = "flex";
		} else {
			showMessage(response.message || "Failed to load users", "error");
		}
	} catch (error) {
		console.error("Error loading users in department:", error);
		showMessage("An error occurred while loading users", "error");
	}
}

function closeUDModal() {
	document.getElementById("usersInDeptModal").classList.add("hidden");
	document.getElementById("usersInDeptModal").style.display = "none";
}

async function archiveDepartment(id) {
	if (!confirm("Are you sure you want to archive this department?")) return;

	try {
		const response = await fetch(API_ENDPOINTS.DEPARTMENTS_LIST, {
			method: "PATCH",
			headers: getAuthHeaders(),
			body: JSON.stringify({ id, action: "archive" }),
		});

		const result = await response.json();

		if (result.success) {
			showMessage("Department archived successfully", "success");
			loadDepartments();
		} else {
			showMessage(result.message || "Failed to archive department", "error");
		}
	} catch (error) {
		console.error("Error archiving department:", error);
		showMessage("An error occurred while archiving the department", "error");
	}
}

async function restoreDepartment(id) {
	if (!confirm("Are you sure you want to restore this department?")) return;

	try {
		const response = await fetch(API_ENDPOINTS.DEPARTMENTS_LIST, {
			method: "PATCH",
			headers: getAuthHeaders(),
			body: JSON.stringify({ id, action: "restore" }),
		});

		const result = await response.json();

		if (result.success) {
			showMessage("Department restored successfully", "success");
			loadDepartments();
		} else {
			showMessage(result.message || "Failed to restore department", "error");
		}
	} catch (error) {
		console.error("Error restoring department:", error);
		showMessage("An error occurred while restoring the department", "error");
	}
}

async function deleteDepartment(id) {
	if (
		!confirm(
			"Are you sure you want to permanently delete this department? This action cannot be undone."
		)
	)
		return;

	try {
		const response = await fetch(API_ENDPOINTS.DEPARTMENTS_LIST, {
			method: "DELETE",
			headers: getAuthHeaders(),
			body: JSON.stringify({ id }),
		});

		const result = await response.json();

		if (result.success) {
			showMessage("Department deleted successfully", "success");
			loadDepartments();
		} else {
			showMessage(result.message || "Failed to delete department", "error");
		}
	} catch (error) {
		console.error("Error deleting department:", error);
		showMessage("An error occurred while deleting the department", "error");
	}
}

window.onclick = (event) => {
	const modal = document.getElementById("departmentModal");
	if (event.target === modal) {
		closeModal();
	}
};
