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

let attendances = [];
let services = [];
let currentPage = 1;
const itemsPerPage = 15;

document.addEventListener("DOMContentLoaded", () => {
	loadServices();
	loadAttendances();
	setupEventListeners();
});

function setupEventListeners() {
	document
		.getElementById("searchInput")
		.addEventListener("input", filterAttendances);
	document
		.getElementById("serviceFilter")
		.addEventListener("change", filterAttendances);
	document
		.getElementById("dateFilter")
		.addEventListener("change", filterAttendances);
}

async function loadServices() {
	try {
		const response = await apiRequest(`${API_ENDPOINTS.SERVICES_LIST}`);
		if (response && response.success) {
			services = response.data.services;
			populateServiceFilter();
		}
	} catch (error) {
		console.error("Error loading services:", error);
	}
}

function populateServiceFilter() {
	const select = document.getElementById("serviceFilter");
	services.forEach((service) => {
		const option = document.createElement("option");
		option.value = service.id;
		option.textContent = service.name;
		select.appendChild(option);
	});
}

async function loadAttendances() {
	try {
		const response = await apiRequest(`${API_ENDPOINTS.ATTENDANCES_LIST}`);
		console.log("services", response);
		if (response && response.success) {
			attendances = response.data.attendance;
			renderAttendances();
		} else {
			showError("Failed to load attendances");
		}
	} catch (error) {
		console.error("Error loading attendances:", error);
		showError("Failed to load attendances");
	}
}

function filterAttendances() {
	const searchTerm = document.getElementById("searchInput").value.toLowerCase();
	const serviceFilter = document.getElementById("serviceFilter").value;
	const dateFilter = document.getElementById("dateFilter").value;

	const filtered = attendances.filter((attendance) => {
		const matchesSearch =
			attendance.user_name.toLowerCase().includes(searchTerm) ||
			attendance.service_name.toLowerCase().includes(searchTerm);
		const matchesService =
			!serviceFilter || attendance.service_id == serviceFilter;
		const matchesDate = !dateFilter || attendance.date === dateFilter;
		return matchesSearch && matchesService && matchesDate;
	});

	renderAttendances(filtered);
}

function renderAttendances(attendancesToRender = attendances) {
	const tbody = document.getElementById("attendancesTableBody");

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

	const start = (currentPage - 1) * itemsPerPage;
	const end = start + itemsPerPage;
	const paginatedAttendances = attendancesToRender.slice(start, end);

	tbody.innerHTML = paginatedAttendances
		.map(
			(attendance) => `
        <tr>
            <td>
                <div style="font-weight: 600;">${attendance.user_name}</div>
                <div style="font-size: 12px; color: #888;">${
									attendance.user_email
								}</div>
            </td>
            <td>${attendance.service_name}</td>
            <td>${formatDate(attendance.service_start_date)}</td>
            <td>${formatTime(attendance.clock_in_time)}</td>
            <td>${
							attendance.clock_out_time
								? formatTime(attendance.clock_out_time)
								: '<span style="color: #888;">--</span>'
						}</td>
            <td>${
							attendance.time_spent
								? formatDuration(attendance.time_spent)
								: '<span style="color: #888;">--</span>'
						}</td>
            <td>${getStatusBadge(attendance.clock_out_time)}</td>
        </tr>
    `
		)
		.join("");

	renderPagination(attendancesToRender.length);
}

function getStatusBadge(clockOutTime) {
	if (clockOutTime) {
		return '<span class="badge success">Completed</span>';
	} else {
		return '<span class="badge warning">In Progress</span>';
	}
}

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

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

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

	for (let i = 1; i <= totalPages; i++) {
		if (
			i === 1 ||
			i === totalPages ||
			(i >= currentPage - 1 && i <= currentPage + 1)
		) {
			html += `<button onclick="changePage(${i})" ${
				i === currentPage ? 'class="active"' : ""
			}>${i}</button>`;
		} else if (i === currentPage - 2 || i === currentPage + 2) {
			html += '<span style="padding: 8px;">...</span>';
		}
	}

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

	pagination.innerHTML = html;
}

function changePage(page) {
	const totalPages = Math.ceil(attendances.length / itemsPerPage);
	if (page < 1 || page > totalPages) return;
	currentPage = page;
	renderAttendances();
}

function exportAttendances() {
	// Create CSV content
	let csv =
		"User Name,User Email,Service,Date,Clock In,Clock Out,Duration,Status\n";

	attendances.forEach((attendance) => {
		csv += `"${attendance.user_name}","${attendance.user_email}","${attendance.service_name}",`;
		csv += `"${formatDate(attendance.date)}","${formatTime(
			attendance.clock_in_time
		)}",`;
		csv += `"${
			attendance.clock_out_time ? formatTime(attendance.clock_out_time) : "--"
		}",`;
		csv += `"${
			attendance.time_spent ? formatDuration(attendance.time_spent) : "--"
		}",`;
		csv += `"${attendance.clock_out_time ? "Completed" : "In Progress"}"\n`;
	});

	// Download CSV
	const blob = new Blob([csv], { type: "text/csv" });
	const url = window.URL.createObjectURL(blob);
	const a = document.createElement("a");
	a.href = url;
	a.download = `attendances_${new Date().toISOString().split("T")[0]}.csv`;
	a.click();
	window.URL.revokeObjectURL(url);
}

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

function formatTime(timeString) {
	if (!timeString) return "--";
	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 formatDuration(minutes) {
	const hours = Math.floor(minutes / 60);
	const mins = minutes % 60;
	return `${hours}h ${mins}m`;
}

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

function handleLogout() {
	localStorage.removeItem("admin_token");
	window.location.href = "login.html";
}

function showError(message) {
	showMessage(message, "error");
}
