const auth = requireAuth();

if (!auth) {
	// Redirect handled by checkAdminAuth
} else {
	// 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]}`;
}

const showToast = (message, type) => {
	// Placeholder for showToast function
	showMessage(message, type);
	console.log(`Toast: ${message} (${type})`);
};

const QRCode = {
	toCanvas: (qrCode, options, callback) => {
		// Placeholder for QRCode.toCanvas function
		callback(null, document.createElement("canvas"));
	},
}; // Placeholder for QRCode object

let allRewards = [];
let filteredRewards = [];
let currentPage = 1;
const itemsPerPage = 20;
let editingRewardId = null;

document.addEventListener("DOMContentLoaded", () => {
	//loadAdminProfile();
	loadRewardsStats();
	loadRewards();
	loadRedeemModalData();

	// Event listeners
	document
		.getElementById("searchInput")
		.addEventListener("input", filterRewards);
	document
		.getElementById("statusFilter")
		.addEventListener("change", filterRewards);
});

async function loadRewardsStats() {
	try {
		const response = await apiRequest(API_ENDPOINTS.REWARDS_LIST);
		const rewards = response.data.rewards || [];

		const totalRewards = rewards.length;
		const activeRewards = rewards.filter((r) => r.archived == 0).length;
		const archivedRewards = rewards.filter((r) => r.archived == 1).length;

		document.getElementById("totalRewards").textContent = totalRewards;
		document.getElementById("activeRewards").textContent = activeRewards;
		document.getElementById("archivedRewards").textContent = archivedRewards;

		document.getElementById("totalRedemptions").textContent = "0"; // Will be updated when redemptions API is available
	} catch (error) {
		console.error("Failed to load rewards stats:", error);
	}
}

async function loadRewards() {
	try {
		const response = await apiRequest(API_ENDPOINTS.REWARDS_LIST);
		allRewards = response.data.rewards || [];
		filteredRewards = [...allRewards];

		displayRewards();
	} catch (error) {
		console.error("Failed to load rewards:", error);
		showToast("Failed to load rewards", "error");
		document.getElementById("rewardsTableBody").innerHTML =
			'<tr><td colspan="7" style="text-align: center; padding: 40px;">Failed to load rewards</td></tr>';
	}
}

// load services and rewards for redeem modal
async function loadRedeemModalData() {
	try {
		const rewardsResponse = await apiRequest(API_ENDPOINTS.REWARDS_LIST);
		const servicesResponse = await apiRequest(API_ENDPOINTS.SERVICES_LIST);
		const rewards = rewardsResponse.data.rewards || [];
		const services = servicesResponse.data.services || [];

		const rewardSelect = document.getElementById("redeemRewardSelect");
		rewardSelect.innerHTML = '<option value="">Select a reward</option>';
		rewards.forEach((reward) => {
			const option = document.createElement("option");
			option.value = reward.id;
			option.textContent = reward.name;
			rewardSelect.appendChild(option);
		});
		const serviceSelect = document.getElementById("redeemServiceSelect");
		serviceSelect.innerHTML = '<option value="">Select a service</option>';
		services.forEach((service) => {
			const option = document.createElement("option");
			option.value = service.id;
			option.textContent = service.name;
			serviceSelect.appendChild(option);
		});
	} catch (error) {
		console.error("Failed to load redeem modal data:", error);
	}
}

// filter rewards based on search and status
function filterRewards() {
	const searchTerm = document.getElementById("searchInput").value.toLowerCase();
	const statusFilter = document.getElementById("statusFilter").value;

	filteredRewards = allRewards.filter((reward) => {
		const matchesSearch =
			reward.name.toLowerCase().includes(searchTerm) ||
			(reward.description &&
				reward.description.toLowerCase().includes(searchTerm));

		const matchesStatus =
			!statusFilter ||
			(statusFilter === "active" && reward.archived == 0) ||
			(statusFilter === "archived" && reward.archived == 1);

		return matchesSearch && matchesStatus;
	});

	currentPage = 1;
	displayRewards();
}

function displayRewards() {
	const tbody = document.getElementById("rewardsTableBody");

	if (filteredRewards.length === 0) {
		tbody.innerHTML =
			'<tr><td colspan="7" style="text-align: center; padding: 40px;">No rewards found</td></tr>';
		document.getElementById("pagination").innerHTML = "";
		return;
	}

	const startIndex = (currentPage - 1) * itemsPerPage;
	const endIndex = startIndex + itemsPerPage;
	const pageRewards = filteredRewards.slice(startIndex, endIndex);

	tbody.innerHTML = "";

	pageRewards.forEach((reward) => {
		const row = document.createElement("tr");

		const createdDate = formatDate(reward.created_at);
		const statusBadge =
			reward.archived == 0
				? '<span class="status-badge status-active">Active</span>'
				: '<span class="status-badge status-past">Archived</span>';

		row.innerHTML = `
			<td>#${reward.id}</td>
			<td>${reward.name}</td>
			<td>${reward.description || "--"}</td>
			<td>${reward.attendance_required || reward.points_required || 0}</td>
			<td>${statusBadge}</td>
			<td>${createdDate}</td>
			<td>
				<div class="action-buttons">
                    <button class="btn-icon" onclick="viewRewardServices(${
											reward.id
										})" title="View Service Rewards">
                        <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="M15 10l4.553-2.276A2 2 0 0122 9.618v4.764a2 2 0 01-1.447 1.894L15 14M4 6h16M4 12h16m-7 6h7"></path>
                        </svg>
                    </button>
                    ${
											reward.archived == 0
												? `<button class="btn-icon" onclick="openSetupServiceRewardModal(${reward.id})" title="Setup Service Reward">
                        <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="M12 4v16m8-8H4"></path>
                        </svg>
                    </button>`
												: ""
										}
					<button class="btn-icon" onclick="editReward(${reward.id})" title="Edit Reward">
						<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>
					${
						reward.archived == 0
							? `<button class="btn-icon btn-danger" onclick="openArchiveModal(${reward.id})" title="Archive Reward">
							<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="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 btn-info" onclick="restoreReward(${reward.id})" title="Restore Reward">
							<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="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 btn-danger" onclick="deleteReward(${
						reward.id
					})" title="Delete Reward">
						<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>
		`;

		tbody.appendChild(row);
	});

	renderPagination();
}

function renderPagination() {
	const totalPages = Math.ceil(filteredRewards.length / itemsPerPage);
	const paginationContainer = document.getElementById("pagination");

	if (totalPages <= 1) {
		paginationContainer.innerHTML = "";
		return;
	}

	let html = "";

	// Previous button
	html += `<button class="pagination-btn" ${
		currentPage === 1 ? "disabled" : ""
	} onclick="changePage(${currentPage - 1})">Previous</button>`;

	// Page numbers
	for (let i = 1; i <= totalPages; i++) {
		if (
			i === 1 ||
			i === totalPages ||
			(i >= currentPage - 2 && i <= currentPage + 2)
		) {
			html += `<button class="pagination-btn ${
				i === currentPage ? "active" : ""
			}" onclick="changePage(${i})">${i}</button>`;
		} else if (i === currentPage - 3 || i === currentPage + 3) {
			html += `<span class="pagination-ellipsis">...</span>`;
		}
	}

	// Next button
	html += `<button class="pagination-btn" ${
		currentPage === totalPages ? "disabled" : ""
	} onclick="changePage(${currentPage + 1})">Next</button>`;

	paginationContainer.innerHTML = html;
}

function changePage(page) {
	currentPage = page;
	displayRewards();
}

function viewQRCode(qrCode) {
	const modal = document.getElementById("qrModal");
	const container = document.getElementById("qrCodeContainer");

	container.innerHTML = "";

	QRCode.toCanvas(
		qrCode,
		{
			width: 250,
			margin: 2,
			color: {
				dark: "#000000",
				light: "#ffffff",
			},
		},
		(error, canvas) => {
			if (error) {
				console.error("QR code generation error:", error);
				container.innerHTML =
					'<p style="color: #888;">Failed to generate QR code</p>';
			} else {
				container.appendChild(canvas);
			}
		}
	);

	modal.classList.add("active");
	modal.style.display = "flex";
}

function closeQRModal() {
	document.getElementById("qrModal").classList.remove("active");
	document.getElementById("qrModal").style.display = "flex";
}

function openRedeemModal() {
	document.getElementById("redeemModal").classList.add("active");
	document.getElementById("redeemModal").style.display = "flex";
}

function closeRedeemModal() {
	document.getElementById("redeemModal").classList.remove("active");
	document.getElementById("redeemModal").style.display = "none";
}

async function confirmRedeem() {
	const rewardId = document.getElementById("redeemRewardId").value;
	const notes = document.getElementById("redeemNotes").value;

	try {
		await apiRequest(API_ENDPOINTS.REWARDS_REDEEM, {
			method: "POST",
			body: JSON.stringify({ reward_id: rewardId, notes }),
		});

		showToast("Reward redeemed successfully", "success");
		closeRedeemModal();
		loadRewardsStats();
		loadRewards();
	} catch (error) {
		console.error("Failed to redeem reward:", error);
		showToast(error.message || "Failed to redeem reward", "error");
	}
}

function openArchiveModal(rewardId) {
	document.getElementById("archiveRewardId").value = rewardId;
	document.getElementById("archiveModal").classList.add("active");
	document.getElementById("archiveModal").style.display = "flex";
}

function closeArchiveModal() {
	document.getElementById("archiveModal").classList.remove("active");
	document.getElementById("archiveModal").style.display = "flex";
}

async function confirmArchive() {
	const rewardId = document.getElementById("archiveRewardId").value;

	try {
		await apiRequest(`${API_ENDPOINTS.REWARDS_LIST}?id=${rewardId}`, {
			method: "PUT",
			body: JSON.stringify({ archived: 0 }),
		});

		showToast("Reward archived successfully", "success");
		closeArchiveModal();
		loadRewardsStats();
		loadRewards();
	} catch (error) {
		console.error("Failed to archive reward:", error);
		showToast(error.message || "Failed to archive reward", "error");
	}
}

async function restoreReward(rewardId) {
	if (!confirm("Are you sure you want to restore this reward?")) return;

	try {
		await apiRequest(`${API_ENDPOINTS.REWARDS_LIST}?id=${rewardId}`, {
			method: "PUT",
			body: JSON.stringify({ archived: 1 }),
		});

		showToast("Reward restored successfully", "success");
		loadRewardsStats();
		loadRewards();
	} catch (error) {
		console.error("Failed to restore reward:", error);
		showToast(error.message || "Failed to restore reward", "error");
	}
}

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

	try {
		await apiRequest(API_ENDPOINTS.REWARDS_LIST, {
			method: "DELETE",
			body: JSON.stringify({ id: rewardId }),
		});

		showToast("Reward deleted successfully", "success");
		loadRewardsStats();
		loadRewards();
	} catch (error) {
		console.error("Failed to delete reward:", error);
		showToast(error.message || "Failed to delete reward", "error");
	}
}

function exportRewards() {
	const csv = convertToCSV(filteredRewards);
	downloadCSV(
		csv,
		`rewards_export_${new Date().toISOString().split("T")[0]}.csv`
	);
	showToast("Rewards exported successfully", "success");
}

function convertToCSV(data) {
	const headers = [
		"Reward ID",
		"User",
		"Service",
		"Created Date",
		"Status",
		"Redeemed Date",
		"QR Code",
	];
	const rows = data.map((reward) => [
		reward.id,
		reward.user_name,
		reward.service_name,
		formatDate(reward.created_at),
		reward.archived ? "Active" : "Archived",
		reward.redeemed_at ? formatDate(reward.redeemed_at) : "--",
		reward.qr_code,
	]);

	return [headers, ...rows].map((row) => row.join(",")).join("\n");
}

function downloadCSV(csv, filename) {
	const blob = new Blob([csv], { type: "text/csv" });
	const url = window.URL.createObjectURL(blob);
	const a = document.createElement("a");
	a.href = url;
	a.download = filename;
	a.click();
	window.URL.revokeObjectURL(url);
}

function openCreateModal() {
	editingRewardId = null;
	alert("here");
	document.getElementById("modalTitle").textContent = "Create Reward";
	document.getElementById("rewardId").value = "";
	document.getElementById("rewardName").value = "";
	document.getElementById("rewardDescription").value = "";
	document.getElementById("rewardAttendance").value = "";
	document.getElementById("createModal").classList.add("active");
	document.getElementById("createModal").style.display = "flex";
}

function closeCreateModal() {
	document.getElementById("createModal").classList.remove("active");
	document.getElementById("createModal").style.display = "none";
	editingRewardId = null;
}

function editReward(rewardId) {
	const reward = allRewards.find((r) => r.id === rewardId);
	if (!reward) return;

	editingRewardId = rewardId;
	document.getElementById("modalTitle").textContent = "Edit Reward";
	document.getElementById("rewardId").value = reward.id;
	document.getElementById("rewardName").value = reward.name;
	document.getElementById("rewardDescription").value = reward.description || "";
	document.getElementById("rewardAttendance").value =
		reward.attendance_required || reward.points_required || 0;
	document.getElementById("createModal").classList.add("active");
	document.getElementById("createModal").style.display = "flex";
}

async function saveReward() {
	const name = document.getElementById("rewardName").value.trim();
	const description = document.getElementById("rewardDescription").value.trim();
	// const attendance = document.getElementById("rewardAttendance").value;

	if (!name) {
		showToast("Please fill in all required fields", "error");
		return;
	}

	const rewardData = {
		name,
		description,
		attendance_required: Number.parseInt(attendance),
	};

	try {
		if (editingRewardId) {
			// Update existing reward
			await apiRequest(`${API_ENDPOINTS.REWARDS_LIST}?id=${editingRewardId}`, {
				method: "PUT",
				body: JSON.stringify(rewardData),
			});
			showToast("Reward updated successfully", "success");
		} else {
			// Create new reward
			await apiRequest(API_ENDPOINTS.REWARDS_LIST, {
				method: "POST",
				body: JSON.stringify(rewardData),
			});
			showToast("Reward created successfully", "success");
		}

		closeCreateModal();
		loadRewardsStats();
		loadRewards();
	} catch (error) {
		console.error("Failed to save reward:", error);
		showToast(error.message || "Failed to save reward", "error");
	}
}

function openSetupServiceRewardModal(rewardId) {
	document.getElementById("setupServiceRewardId").value = rewardId;
	document.getElementById("setupServiceModal").classList.add("active");
	document.getElementById("setupServiceModal").style.display = "flex";
}

function closeSetupServiceRewardModal() {
	document.getElementById("setupServiceModal").classList.remove("active");
	document.getElementById("setupServiceModal").style.display = "none";
}

function editServiceReward(rewardId) {
	const reward = allRewards.find((r) => r.id === rewardId);
	if (!reward) return;

	editingRewardId = rewardId;
	document.getElementById("modalTitle").textContent = "Edit Service Reward";
	document.getElementById("setupServiceRewardId").value = reward.id;
	document.getElementById("setupServiceSelect").value = reward.service_id || "";
	document.getElementById("setupPointsRequired").value =
		reward.points_required || "";
	document.getElementById("setupServiceModal").classList.add("active");
	document.getElementById("setupServiceModal").style.display = "flex";
}

async function saveServiceRewardSetup() {
	const rewardId = document.getElementById("setupServiceRewardId").value;
	const serviceId = document.getElementById("setupServiceSelect").value;
	const pointsRequired = document.getElementById("setupPointsRequired").value;
	if (!serviceId || !pointsRequired) {
		showToast("Please fill in all required fields", "error");
		return;
	}
	try {
		await apiRequest(API_ENDPOINTS.SERVICE_REWARDS_SETUP, {
			method: "POST",
			body: JSON.stringify({
				reward_id: rewardId,
				service_id: serviceId,
				points_required: Number.parseInt(pointsRequired),
			}),
		});
		showToast("Service reward setup saved successfully", "success");
		closeSetupServiceRewardModal();
	} catch (error) {
		console.error("Failed to save service reward setup:", error);
		showToast(error.message || "Failed to save service reward setup", "error");
	}
}
