/**
 * Dashboard JS
 * Handles admin dashboard interactions and data loading
 */

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

	// Load dashboard data
	loadDashboardStats();
	loadRecentAttendances();
}

async function loadDashboardStats() {
	try {
		const response = await apiRequest(API_ENDPOINTS.DASHBOARD_STATS);

		if (response && response.success) {
			document.getElementById("totalUsers").textContent =
				response.data.stats.total_users || 0;
			document.getElementById("totalAttendances").textContent =
				response.data.stats.total_attendances || 0;
			document.getElementById("totalServices").textContent =
				response.data.stats.total_services || 0;
			document.getElementById("activeTickets").textContent =
				response.data.stats.active_tickets || 0;
		}
	} catch (error) {
		console.error("Error loading dashboard stats:", error);
	}
}

async function loadRecentAttendances() {
	try {
		const response = await apiRequest(API_ENDPOINTS.DASHBOARD_STATS);
		const tbody = document.getElementById("recentAttendances");

		if (
			response &&
			response.success &&
			response.data.recent_attendance &&
			response.data.recent_attendance.length > 0
		) {
			tbody.innerHTML = response.data.recent_attendance
				.map(
					(attendance) => `
                <tr>
                    <td>
                        <div style="display: flex; align-items: center; gap: 8px;">
                            ${
															attendance.avatar_url
																? `<img src="${attendance.avatar_url}" alt="${attendance.first_name}" style="width: 32px; height: 32px; border-radius: 50%; object-fit: cover;">`
																: `<div style="width: 32px; height: 32px; border-radius: 50%; background: #d4af37; color: white; display: flex; align-items: center; justify-content: center; font-weight: 600;">${attendance.first_name[0]}${attendance.last_name[0]}</div>`
														}
                            <div>
                                <div style="font-weight: 500;">${
																	attendance.first_name
																} ${attendance.last_name}</div>
                                <div style="font-size: 12px; color: #888;">${
																	attendance.department_name || "No Department"
																}</div>
                            </div>
                        </div>
                    </td>
                    <td>
                        <div>
                            <div style="font-weight: 500;">${
															attendance.service_name
														}</div>
                            <div style="font-size: 12px; color: #888;">${formatDate(
															attendance.occurrence_date
														)} at ${formatTime(attendance.start_time)}</div>
                        </div>
                    </td>
                    <td>${formatDateTime(attendance.clock_in_time)}</td>
                    <td>${
											attendance.clock_out_time
												? formatDateTime(attendance.clock_out_time)
												: "-"
										}</td>
                    <td>${
											attendance.time_spent
												? formatDuration(attendance.time_spent)
												: "-"
										}</td>
                    <td>
                        <span class="badge ${
													attendance.clock_out_time ? "success" : "warning"
												}">
                            ${
															attendance.clock_out_time
																? "Completed"
																: "In Progress"
														}
                        </span>
                    </td>
                </tr>
            `
				)
				.join("");
		} else {
			tbody.innerHTML = `
                <tr>
                    <td colspan="6" style="text-align: center; padding: 40px; color: #888;">
                        No recent attendances found
                    </td>
                </tr>
            `;
		}
	} catch (error) {
		console.error("Error loading recent attendances:", error);
		document.getElementById("recentAttendances").innerHTML = `
            <tr>
                <td colspan="6" style="text-align: center; padding: 40px; color: #ef4444;">
                    Error loading attendances
                </td>
            </tr>
        `;
	}
}

function formatDateTime(dateString) {
	const date = new Date(dateString);
	return date.toLocaleString("en-US", {
		month: "short",
		day: "numeric",
		year: "numeric",
		hour: "2-digit",
		minute: "2-digit",
	});
}

function formatDuration(seconds) {
	const hours = Math.floor(seconds / 3600);
	const minutes = Math.floor((seconds % 3600) / 60);
	return `${hours}h ${minutes}m`;
}

function formatDate(dateString) {
	const date = new Date(dateString);
	return date.toLocaleDateString("en-US", {
		month: "short",
		day: "numeric",
		year: "numeric",
	});
}

function formatTime(timeString) {
	// timeString is in HH:MM:SS format
	const [hours, minutes] = timeString.split(":");
	const hour = Number.parseInt(hours);
	const ampm = hour >= 12 ? "PM" : "AM";
	const displayHour = hour % 12 || 12;
	return `${displayHour}:${minutes} ${ampm}`;
}

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