// Import QRCode library
const QRCode = window.QRCode; // Assuming QRCode is available globally

// Check authentication
requireAuth();

// Initialize
document.addEventListener("DOMContentLoaded", () => {
	loadUserProfile();
	loadTicketProgress();
	loadTickets();
});

// Show loading state for progress
function showProgressLoadingState() {
	const container = document.getElementById("progressList");
	container.innerHTML = `
		<div class="loading-container" style="text-align: center; padding: 3rem;">
			<div class="spinner"></div>
			<p style="margin-top: 1rem; color: var(--text-secondary);">Loading your progress...</p>
		</div>
	`;
}

// Show loading state for tickets
function showTicketsLoadingState() {
	const container = document.getElementById("ticketsList");
	container.innerHTML = `
		<div class="loading-container" style="text-align: center; padding: 3rem;">
			<div class="spinner"></div>
			<p style="margin-top: 1rem; color: var(--text-secondary);">Loading your tickets...</p>
		</div>
	`;
}

// Show error state
function showErrorState(container, message, retryFunction) {
	const element = document.getElementById(container);
	element.innerHTML = `
		<div style="text-align: center; padding: 3rem;">
			<div style="font-size: 3rem; margin-bottom: 1rem;">⚠️</div>
			<p style="color: var(--error-red); margin-bottom: 1rem; font-weight: 500;">${message}</p>
			<button class="btn btn-primary" onclick="${retryFunction}">Retry</button>
		</div>
	`;
}

// Show empty state for progress
function showProgressEmptyState() {
	const container = document.getElementById("progressList");
	container.innerHTML = `
		<div style="text-align: center; padding: 3rem;">
			<div style="font-size: 3rem; margin-bottom: 1rem;">🎯</div>
			<p style="color: var(--text-secondary); font-size: 1.125rem; font-weight: 500;">No reward-based services available</p>
			<p style="color: var(--text-tertiary); font-size: 0.875rem; margin-top: 0.5rem;">Start attending services to earn rewards</p>
		</div>
	`;
}

// Show empty state for tickets
function showTicketsEmptyState() {
	const container = document.getElementById("ticketsList");
	container.innerHTML = `
		<div style="text-align: center; padding: 3rem;">
			<div style="font-size: 3rem; margin-bottom: 1rem;">🎫</div>
			<p style="color: var(--text-secondary); font-size: 1.125rem; font-weight: 500;">No tickets earned yet</p>
			<p style="color: var(--text-tertiary); font-size: 0.875rem; margin-top: 0.5rem;">Keep attending services to earn your first ticket!</p>
		</div>
	`;
}

// Load user profile
async function loadUserProfile() {
	try {
		const response = await apiRequest(API_ENDPOINTS.PROFILE);
		const user = response.data.user;

		const initials = getUserInitials(user.first_name, user.last_name);
		document.getElementById("userAvatar").textContent = initials;
		document.getElementById("profileAvatarLarge").textContent = initials;
		document.getElementById(
			"profileName"
		).textContent = `${user.first_name} ${user.last_name}`;
		document.getElementById("profileEmail").textContent = user.email;

		const departmentEl = document.getElementById("profileCampus");
		if (user.department_name) {
			departmentEl.textContent = user.department_name;
		} else {
			departmentEl.textContent = "--";
		}

		const badgesContainer = document.getElementById("profileBadges");
		badgesContainer.innerHTML = "";

		if (user.role_name) {
			const badge = document.createElement("div");
			badge.className = `badge badge-${user.role_name.toLowerCase()}`;
			badge.textContent =
				user.role_name.charAt(0).toUpperCase() + user.role_name.slice(1);
			badgesContainer.appendChild(badge);
		}

		if (user.is_hod) {
			const badge = document.createElement("div");
			badge.className = "badge badge-hod";
			badge.textContent = "HOD";
			badgesContainer.appendChild(badge);
		}
	} catch (error) {
		console.error("Failed to load profile:", error);
	}
}

// Load ticket progress
async function loadTicketProgress() {
	showProgressLoadingState();

	try {
		const response = await apiRequest(API_ENDPOINTS.TICKET_PROGRESS);
		const progress = response.data.progress;

		displayProgress(progress);
	} catch (error) {
		console.error("Failed to load ticket progress:", error);
		showErrorState(
			"progressList",
			"Failed to load progress",
			"loadTicketProgress()"
		);
	}
}

// Display progress
function displayProgress(progress) {
	const listContainer = document.getElementById("progressList");

	if (progress.length === 0) {
		showProgressEmptyState();
		return;
	}

	listContainer.innerHTML = "";

	progress.forEach((item) => {
		const card = document.createElement("div");
		card.className = "progress-card";

		const percentage = item.progress_percentage.toFixed(0);
		const current = item.current_progress;
		const required = item.tickets_required;

		card.innerHTML = `
            <div class="progress-card-header">
                <div class="service-name-text">${item.service_name}</div>
                <div class="tickets-earned-badge">${
									item.tickets_earned
								} 🎫</div>
            </div>
            <div class="progress-card-body">
                <div class="progress-info">
                    <span class="progress-text">${current} / ${required} attendances</span>
                    <span class="progress-percentage">${percentage}%</span>
                </div>
                <div class="progress-bar">
                    <div class="progress-bar-fill" style="width: ${percentage}%"></div>
                </div>
                <p class="progress-message">
                    ${
											current === 0
												? `Attend ${required} times to earn a ticket`
												: `${required - current} more attendance${
														required - current > 1 ? "s" : ""
												  } to earn your next ticket`
										}
                </p>
            </div>
        `;

		listContainer.appendChild(card);
	});
}

// Load tickets
async function loadTickets() {
	showTicketsLoadingState();

	try {
		const response = await apiRequest(API_ENDPOINTS.TICKETS_LIST);
		const tickets = response.data.tickets;

		displayTickets(tickets);
	} catch (error) {
		console.error("Failed to load tickets:", error);
		showErrorState("ticketsList", "Failed to load tickets", "loadTickets()");
	}
}

// Display tickets
function displayTickets(tickets) {
	const listContainer = document.getElementById("ticketsList");

	if (tickets.length === 0) {
		showTicketsEmptyState();
		return;
	}

	listContainer.innerHTML = "";

	tickets.forEach((ticket) => {
		const card = document.createElement("div");
		card.className = `ticket-card ${
			ticket.is_redeemed ? "ticket-redeemed" : "ticket-active"
		}`;

		const createdDate = new Date(ticket.created_at);
		const dateStr = createdDate.toLocaleDateString("en-US", {
			month: "short",
			day: "numeric",
			year: "numeric",
		});

		const redeemedDate = ticket.redeemed_at
			? new Date(ticket.redeemed_at).toLocaleDateString("en-US", {
					month: "short",
					day: "numeric",
					year: "numeric",
			  })
			: null;

		card.innerHTML = `
            <div class="ticket-card-header">
                <div class="ticket-icon">🎫</div>
                <div class="ticket-info">
                    <div class="ticket-service">${ticket.service_name}</div>
                    <div class="ticket-date">Earned: ${dateStr}</div>
                </div>
                <div class="ticket-status">
                    ${
											ticket.is_redeemed
												? '<span class="status-badge status-past">Redeemed</span>'
												: '<span class="status-badge status-active">Active</span>'
										}
                </div>
            </div>
            <div class="ticket-card-body">
                ${
									ticket.is_redeemed
										? `<p class="ticket-redeemed-text">Redeemed on ${redeemedDate}</p>`
										: `<button class="btn btn-primary" onclick="showQRCode('${ticket.qr_code}')">Show QR Code</button>`
								}
            </div>
        `;

		listContainer.appendChild(card);
	});
}

// Show QR code
function showQRCode(qrCode) {
	const modal = document.getElementById("qrModal");
	const container = document.getElementById("qrCodeContainer");

	// Clear previous QR code
	container.innerHTML =
		'<div class="spinner" style="margin: 2rem auto;"></div>';

	// Generate QR code
	try {
		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 = `
						<div style="text-align: center; padding: 2rem;">
							<p style="color: var(--error-red);">Failed to generate QR code</p>
							<button class="btn btn-secondary" style="margin-top: 1rem;" onclick="closeQRModal()">Close</button>
						</div>
					`;
				} else {
					container.innerHTML = "";
					container.appendChild(canvas);
				}
			}
		);
	} catch (error) {
		console.error("QR generation failed:", error);
		container.innerHTML = `
			<div style="text-align: center; padding: 2rem;">
				<p style="color: var(--error-red);">QR code library not loaded</p>
				<button class="btn btn-secondary" style="margin-top: 1rem;" onclick="closeQRModal()">Close</button>
			</div>
		`;
	}

	modal.classList.add("active");
}

// Close QR modal
function closeQRModal() {
	document.getElementById("qrModal").classList.remove("active");
}

// Open profile modal
function openProfile() {
	document.getElementById("profileModal").classList.add("active");
}

// Close profile modal
function closeProfile() {
	document.getElementById("profileModal").classList.remove("active");
}

// Handle logout
async function handleLogout() {
	try {
		await apiRequest(API_ENDPOINTS.LOGOUT, {
			method: "POST",
		});
	} catch (error) {
		console.error("Logout error:", error);
	} finally {
		removeAuthToken();
		window.location.href = "login.html";
	}
}
