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]}`;
}

// State
let currentReportType = "general";
let currentReportData = null;
let charts = [];

// Initialize
document.addEventListener("DOMContentLoaded", () => {
	//loadAdminProfile()
	loadUsers();
	loadServices();
	initializeDateRange();
});

// Initialize date range
function initializeDateRange() {
	const endDate = new Date();
	const startDate = new Date();
	startDate.setDate(startDate.getDate() - 30);

	document.getElementById("startDate").valueAsDate = startDate;
	document.getElementById("endDate").valueAsDate = endDate;
}

// Load users for filter
async function loadUsers() {
	try {
		const response = await apiRequest(API_ENDPOINTS.USERS_LIST);
		const users = response.data.users;

		const select = document.getElementById("userFilter");
		users.forEach((user) => {
			const option = document.createElement("option");
			option.value = user.id;
			option.textContent = `${user.first_name} ${user.last_name} (${user.email})`;
			select.appendChild(option);
		});
	} catch (error) {
		console.error("Failed to load users:", error);
	}
}

// Load services for filter
async function loadServices() {
	try {
		const response = await apiRequest(API_ENDPOINTS.SERVICES_LIST);
		const services = response.data.services;

		const select = document.getElementById("serviceFilter");
		services.forEach((service) => {
			const option = document.createElement("option");
			option.value = service.id;
			option.textContent = service.name;
			select.appendChild(option);
		});
	} catch (error) {
		console.error("Failed to load services:", error);
	}
}

// Select report type
function selectReportType(type) {
	currentReportType = type;

	// Update active card
	document.querySelectorAll(".report-type-card").forEach((card) => {
		card.classList.remove("active");
	});
	document.querySelector(`[data-type="${type}"]`).classList.add("active");

	// Show/hide filters
	document.getElementById("userFilterGroup").style.display =
		type === "user" ? "block" : "none";
	document.getElementById("serviceFilterGroup").style.display =
		type === "service" ? "block" : "none";

	// Clear report content
	document.getElementById("reportContent").innerHTML = `
		<div class="report-placeholder">
			<svg width="64" height="64" fill="none" stroke="currentColor" viewBox="0 0 24 24">
				<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 17v-2m3 2v-4m3 4v-6m2 10H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
			</svg>
			<h3>Click "Generate Report" to view ${type} analytics</h3>
		</div>
	`;
}

// Generate report
async function generateReport() {
	const startDate = document.getElementById("startDate").value;
	const endDate = document.getElementById("endDate").value;

	if (!startDate || !endDate) {
		showToast("Please select date range", "error");
		return;
	}

	// Destroy existing charts
	charts.forEach((chart) => chart.destroy());
	charts = [];

	// Show loading
	document.getElementById("reportContent").innerHTML = `
		<div style="text-align: center; padding: 60px;">
			<div class="spinner" style="margin: 0 auto;"></div>
			<p style="margin-top: 20px; color: #888;">Generating report...</p>
		</div>
	`;

	try {
		let endpoint = `${API_ENDPOINTS.REPORTS}?type=${currentReportType}&start_date=${startDate}&end_date=${endDate}`;

		if (currentReportType === "user") {
			const userId = document.getElementById("userFilter").value;
			if (!userId) {
				showToast("Please select a user", "error");
				return;
			}
			endpoint += `&user_id=${userId}`;
		} else if (currentReportType === "service") {
			const serviceId = document.getElementById("serviceFilter").value;
			if (!serviceId) {
				showToast("Please select a service", "error");
				return;
			}
			endpoint += `&service_id=${serviceId}`;
		}

		const response = await apiRequest(endpoint);
		currentReportData = response.data;

		displayReport();
	} catch (error) {
		console.error("Failed to generate report:", error);
		showToast(error.message || "Failed to generate report", "error");
		document.getElementById("reportContent").innerHTML = `
			<div class="report-placeholder">
				<p style="color: #f44336;">Failed to generate report. Please try again.</p>
			</div>
		`;
	}
}

// Display report
function displayReport() {
	const container = document.getElementById("reportContent");

	if (currentReportType === "general") {
		displayGeneralReport(container);
	} else if (currentReportType === "user") {
		displayUserReport(container);
	} else if (currentReportType === "service") {
		displayServiceReport(container);
	} else if (currentReportType === "attendance") {
		displayAttendanceReport(container);
	}
}

// Display general report
function displayGeneralReport(container) {
	const report = currentReportData.report;
	const attendanceByService = currentReportData.attendance_by_service || [];

	container.innerHTML = `
		<div class="report-section">
			<h2 class="report-title">General Statistics</h2>
			<div class="stats-grid" style="grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));">
				<div class="stat-card">
					<div class="stat-icon primary">
						<svg width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24">
							<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z"></path>
						</svg>
					</div>
					<div class="stat-value">${report.total_users || 0}</div>
					<div class="stat-label">Total Users</div>
				</div>
				<div class="stat-card">
					<div class="stat-icon info">
						<svg width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24">
							<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"></path>
						</svg>
					</div>
					<div class="stat-value">${report.total_services || 0}</div>
					<div class="stat-label">Total Services</div>
				</div>
				<div class="stat-card">
					<div class="stat-icon success">
						<svg width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24">
							<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
						</svg>
					</div>
					<div class="stat-value">${report.total_attendance || 0}</div>
					<div class="stat-label">Total Attendances</div>
				</div>
				<div class="stat-card">
					<div class="stat-icon warning">
						<svg width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24">
							<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 5v2m0 4v2m0 4v2M5 5a2 2 0 00-2 2v3a2 2 0 110 4v3a2 2 0 002 2h14a2 2 0 002-2v-3a2 2 0 110-4V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"></path>
						</svg>
					</div>
					<div class="stat-value">${report.total_tickets || 0}</div>
					<div class="stat-label">Total Tickets</div>
				</div>
			</div>
		</div>
		
		<div class="report-section">
			<h2 class="report-title">Attendance by Service</h2>
			<div class="chart-container">
				<canvas id="attendanceChart"></canvas>
			</div>
		</div>
		
		<div class="report-section">
			<h2 class="report-title">Service Breakdown</h2>
			<table class="data-table">
				<thead>
					<tr>
						<th>Service Name</th>
						<th>Attendance Count</th>
						<th>Percentage</th>
					</tr>
				</thead>
				<tbody>
					${attendanceByService
						.map((item) => {
							const percentage =
								report.total_attendance > 0
									? (
											(item.attendance_count / report.total_attendance) *
											100
									  ).toFixed(1)
									: 0;
							return `
							<tr>
								<td><strong>${item.name}</strong></td>
								<td>${item.attendance_count}</td>
								<td>
									<div style="display: flex; align-items: center; gap: 12px;">
										<div class="progress-bar">
											<div class="progress-fill" style="width: ${percentage}%"></div>
										</div>
										<span style="min-width: 50px; font-weight: 600; color: var(--primary-color);">${percentage}%</span>
									</div>
								</td>
							</tr>
						`;
						})
						.join("")}
				</tbody>
			</table>
		</div>
	`;

	const ctx = document.getElementById("attendanceChart").getContext("2d");
	const chart = new Chart(ctx, {
		type: "bar",
		data: {
			labels: attendanceByService.map((item) => item.name),
			datasets: [
				{
					label: "Attendance Count",
					data: attendanceByService.map((item) => item.attendance_count),
					backgroundColor: "rgba(253, 185, 19, 0.8)",
					borderColor: "#FDB913",
					borderWidth: 2,
					borderRadius: 8,
					hoverBackgroundColor: "#FDB913",
				},
			],
		},
		options: {
			responsive: true,
			maintainAspectRatio: false,
			plugins: {
				legend: {
					display: false,
				},
				tooltip: {
					backgroundColor: "#1a1a1a",
					titleColor: "#fff",
					bodyColor: "#fff",
					borderColor: "#2a2a2a",
					borderWidth: 1,
					padding: 12,
					displayColors: false,
					callbacks: {
						label: (context) => `Attendance: ${context.parsed.y}`,
					},
				},
			},
			scales: {
				y: {
					beginAtZero: true,
					ticks: {
						stepSize: 1,
						color: "#888",
						font: {
							size: 12,
						},
					},
					grid: {
						color: "#2a2a2a",
						drawBorder: false,
					},
				},
				x: {
					ticks: {
						color: "#888",
						font: {
							size: 12,
						},
					},
					grid: {
						display: false,
					},
				},
			},
		},
	});

	charts.push(chart);
}

// Display user report
function displayUserReport(container) {
	const report = currentReportData.report;
	const attendanceDetails = currentReportData.attendance_details || [];

	container.innerHTML = `
		<div class="report-section">
			<h2 class="report-title">User Information</h2>
			<div class="user-info-grid">
				<div class="info-item">
					<label>Name:</label>
					<span>${report.first_name} ${report.last_name}</span>
				</div>
				<div class="info-item">
					<label>Email:</label>
					<span>${report.email}</span>
				</div>
				<div class="info-item">
					<label>Campus:</label>
					<span>${report.department || "--"}</span>
				</div>
				<div class="info-item">
					<label>User Type:</label>
					<span>${report.user_type || "--"}</span>
				</div>
			</div>
		</div>
		
		<div class="report-section">
			<h2 class="report-title">Attendance Summary</h2>
			<div class="stats-grid" style="grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));">
				<div class="stat-card">
					<div class="stat-icon success">
						<svg width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24">
							<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
						</svg>
					</div>
					<div class="stat-value">${report.total_attendance || 0}</div>
					<div class="stat-label">Total Attendances</div>
				</div>
				<div class="stat-card">
					<div class="stat-icon info">
						<svg width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24">
							<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
						</svg>
					</div>
					<div class="stat-value">${formatDuration(report.total_time_spent || 0)}</div>
					<div class="stat-label">Total Time Spent</div>
				</div>
				<div class="stat-card">
					<div class="stat-icon warning">
						<svg width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24">
							<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 5v2m0 4v2m0 4v2M5 5a2 2 0 00-2 2v3a2 2 0 110 4v3a2 2 0 002 2h14a2 2 0 002-2v-3a2 2 0 110-4V7a2 2 0 00-2-2H5z"></path>
						</svg>
					</div>
					<div class="stat-value">${report.total_tickets || 0}</div>
					<div class="stat-label">Tickets Earned</div>
				</div>
			</div>
		</div>
		
		<div class="report-section">
			<h2 class="report-title">Attendance Details</h2>
			<table class="data-table">
				<thead>
					<tr>
						<th>Service</th>
						<th>Clock In</th>
						<th>Clock Out</th>
						<th>Duration</th>
					</tr>
				</thead>
				<tbody>
					${
						attendanceDetails.length > 0
							? attendanceDetails
									.map(
										(item) => `
						<tr>
							<td>${item.service_name}</td>
							<td>${formatDateTime(item.clock_in_time)}</td>
							<td>${item.clock_out_time ? formatDateTime(item.clock_out_time) : "--"}</td>
							<td>${formatDuration(item.time_spent || 0)}</td>
						</tr>
					`
									)
									.join("")
							: '<tr><td colspan="4" style="text-align: center;">No attendance records found</td></tr>'
					}
				</tbody>
			</table>
		</div>
	`;
}

// Display service report
function displayServiceReport(container) {
	const report = currentReportData.report;
	const topAttendees = currentReportData.top_attendees || [];

	container.innerHTML = `
		<div class="report-section">
			<h2 class="report-title">Service Information</h2>
			<div class="user-info-grid">
				<div class="info-item">
					<label>Service Name:</label>
					<span>${report.name}</span>
				</div>
				<div class="info-item">
					<label>Location:</label>
					<span>${report.location}</span>
				</div>
				<div class="info-item">
					<label>Start Time:</label>
					<span>${report.start_time}</span>
				</div>
				<div class="info-item">
					<label>End Time:</label>
					<span>${report.end_time}</span>
				</div>
			</div>
		</div>
		
		<div class="report-section">
			<h2 class="report-title">Service Statistics</h2>
			<div class="stats-grid" style="grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));">
				<div class="stat-card">
					<div class="stat-icon primary">
						<svg width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24">
							<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z"></path>
						</svg>
					</div>
					<div class="stat-value">${report.total_attendees || 0}</div>
					<div class="stat-label">Total Attendees</div>
				</div>
				<div class="stat-card">
					<div class="stat-icon success">
						<svg width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24">
							<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
						</svg>
					</div>
					<div class="stat-value">${report.total_attendance || 0}</div>
					<div class="stat-label">Total Attendances</div>
				</div>
				<div class="stat-card">
					<div class="stat-icon info">
						<svg width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24">
							<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
						</svg>
					</div>
					<div class="stat-value">${formatDuration(report.avg_time_spent || 0)}</div>
					<div class="stat-label">Avg. Time Spent</div>
				</div>
			</div>
		</div>
		
		<div class="report-section">
			<h2 class="report-title">Top Attendees</h2>
			<table class="data-table">
				<thead>
					<tr>
						<th>Rank</th>
						<th>Name</th>
						<th>Email</th>
						<th>Attendance Count</th>
						<th>Total Time</th>
					</tr>
				</thead>
				<tbody>
					${
						topAttendees.length > 0
							? topAttendees
									.map(
										(item, index) => `
						<tr>
							<td>${index + 1}</td>
							<td>${item.first_name} ${item.last_name}</td>
							<td>${item.email}</td>
							<td>${item.attendance_count}</td>
							<td>${formatDuration(item.total_time_spent || 0)}</td>
						</tr>
					`
									)
									.join("")
							: '<tr><td colspan="5" style="text-align: center;">No attendance records found</td></tr>'
					}
				</tbody>
			</table>
		</div>
	`;
}

// Display attendance report
function displayAttendanceReport(container) {
	// Similar to general report but with more detailed attendance breakdown
	displayGeneralReport(container);
}

// Export report
function exportReport() {
	if (!currentReportData) {
		showToast("Please generate a report first", "error");
		return;
	}

	showToast("PDF export functionality coming soon", "info");
}
