// Check authentication
requireAuth();

// State
let allAttendance = [];
let services = [];
let currentPage = 1;
let totalPages = 1;
let isFilterVisible = false;
let filters = {
	service_id: "",
	start_date: "",
	end_date: "",
	is_valid: "",
};
let statistics = null;

// Initialize
document.addEventListener("DOMContentLoaded", () => {
	loadUserProfile();
	loadServices();
	setupFilterHandlers();
	loadAttendanceHistory();
});

// Toggle filter section
function toggleFilters() {
	const filterSection = document.getElementById("filterSection");
	const toggleBtn = document.getElementById("filterToggleBtn");

	isFilterVisible = !isFilterVisible;

	if (isFilterVisible) {
		filterSection.classList.remove("hidden");
		toggleBtn.classList.add("active");
	} else {
		filterSection.classList.add("hidden");
		toggleBtn.classList.remove("active");
		// Reset filters when hiding
		resetFilters();
	}
}

// Setup filter event handlers
function setupFilterHandlers() {
	const serviceFilter = document.getElementById("serviceFilter");
	const startDateFilter = document.getElementById("startDateFilter");
	const endDateFilter = document.getElementById("endDateFilter");
	const validityFilter = document.getElementById("validityFilter");
	const resetButton = document.getElementById("resetFilters");

	if (serviceFilter) {
		serviceFilter.addEventListener("change", () => {
			filters.service_id = serviceFilter.value;
			currentPage = 1;
			loadAttendanceHistory();
		});
	}

	if (startDateFilter) {
		startDateFilter.addEventListener("change", () => {
			filters.start_date = startDateFilter.value;
			currentPage = 1;
			loadAttendanceHistory();
		});
	}

	if (endDateFilter) {
		endDateFilter.addEventListener("change", () => {
			filters.end_date = endDateFilter.value;
			currentPage = 1;
			loadAttendanceHistory();
		});
	}

	if (validityFilter) {
		validityFilter.addEventListener("change", () => {
			filters.is_valid = validityFilter.value;
			currentPage = 1;
			loadAttendanceHistory();
		});
	}

	if (resetButton) {
		resetButton.addEventListener("click", resetFilters);
	}
}

// Reset all filters
function resetFilters() {
	filters = {
		service_id: "",
		start_date: "",
		end_date: "",
		is_valid: "",
	};

	document.getElementById("serviceFilter").value = "";
	const startDateFilter = document.getElementById("startDateFilter");
	const endDateFilter = document.getElementById("endDateFilter");
	const validityFilter = document.getElementById("validityFilter");

	if (startDateFilter) startDateFilter.value = "";
	if (endDateFilter) endDateFilter.value = "";
	if (validityFilter) validityFilter.value = "";

	currentPage = 1;
	loadAttendanceHistory();
}

// 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 = "--";
		}

		// Update badges
		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);
	}
}

async function loadServices() {
	try {
		// Load active service occurrences for today and upcoming
		const response = await apiRequest(API_ENDPOINTS.SERVICES_LIST);
		services = response.data.services || [];

		const filterSelect = document.getElementById("serviceFilter");
		if (filterSelect) {
			filterSelect.innerHTML = '<option value="">All Services</option>';

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

// Load attendance history
async function loadAttendanceHistory() {
	try {
		// Show loading state
		showLoadingState();

		// Build query string with filters
		const queryParams = new URLSearchParams();

		if (filters.service_id) {
			queryParams.append("service_id", filters.service_id);
		}
		if (filters.start_date) {
			queryParams.append("start_date", filters.start_date);
		}
		if (filters.end_date) {
			queryParams.append("end_date", filters.end_date);
		}
		if (filters.is_valid) {
			queryParams.append("is_valid", filters.is_valid);
		}

		// Add pagination
		const limit = 20;
		const offset = (currentPage - 1) * limit;
		queryParams.append("limit", limit);
		queryParams.append("offset", offset);

		const url = `${API_ENDPOINTS.ATTENDANCE_HISTORY}?${queryParams.toString()}`;
		const response = await apiRequest(url);

		allAttendance = response.data.history || [];
		statistics = response.data.statistics || null;

		// Update pagination info
		if (response.data.pagination) {
			totalPages = response.data.pagination.total_pages;
			updatePaginationControls(response.data.pagination);
		}

		// Display statistics if available
		if (statistics) {
			displayStatistics(statistics);
		}

		// Display attendance records
		displayAttendance(allAttendance);

		// Show viewing scope info
		if (response.data.user_permissions) {
			displayViewingScopeInfo(response.data.user_permissions);
		}
	} catch (error) {
		console.error("Failed to load attendance history:", error);
		showErrorState(error.message || "Failed to load attendance history");
	}
}

// Show loading state
function showLoadingState() {
	const listContainer = document.getElementById("attendanceList");
	listContainer.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 attendance records...</p>
		</div>
	`;
}

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

// Display statistics
function displayStatistics(stats) {
	const statsContainer = document.getElementById("statisticsContainer");
	if (!statsContainer) return;

	const validPercentage =
		stats.total_records > 0
			? ((stats.valid_attendances / stats.total_records) * 100).toFixed(1)
			: 0;

	statsContainer.innerHTML = `
		<div class="stats-grid" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 1rem; margin-bottom: 1.5rem;">
			<div class="stat-card" style="background: var(--bg-dark-secondary); padding: 1rem; border-radius: 12px; text-align: center;">
				<div style="font-size: 1.5rem; font-weight: 700; color: var(--primary-gold);">${
					stats.total_records
				}</div>
				<div style="font-size: 0.875rem; color: var(--text-secondary); margin-top: 0.25rem;">Total Records</div>
			</div>
			<div class="stat-card" style="background: var(--bg-dark-secondary); padding: 1rem; border-radius: 12px; text-align: center;">
				<div style="font-size: 1.5rem; font-weight: 700; color: var(--success-green);">${
					stats.valid_attendances
				}</div>
				<div style="font-size: 0.875rem; color: var(--text-secondary); margin-top: 0.25rem;">Valid (${validPercentage}%)</div>
			</div>
			<div class="stat-card" style="background: var(--bg-dark-secondary); padding: 1rem; border-radius: 12px; text-align: center;">
				<div style="font-size: 1.5rem; font-weight: 700; color: var(--error-red);">${
					stats.invalid_attendances
				}</div>
				<div style="font-size: 0.875rem; color: var(--text-secondary); margin-top: 0.25rem;">Invalid</div>
			</div>
			<div class="stat-card" style="background: var(--bg-dark-secondary); padding: 1rem; border-radius: 12px; text-align: center;">
				<div style="font-size: 1.5rem; font-weight: 700; color: var(--text-primary);">${formatDuration(
					stats.average_time_spent
				)}</div>
				<div style="font-size: 0.875rem; color: var(--text-secondary); margin-top: 0.25rem;">Avg Time</div>
			</div>
		</div>
	`;
}

// Display viewing scope info
function displayViewingScopeInfo(permissions) {
	const scopeContainer = document.getElementById("viewingScopeInfo");
	if (!scopeContainer) return;

	let scopeText = "";
	let scopeColor = "var(--text-secondary)";

	if (permissions.viewing_scope === "all") {
		scopeText = "📊 Viewing: All Users";
		scopeColor = "var(--primary-gold)";
	} else if (permissions.viewing_scope === "department") {
		scopeText = "👥 Viewing: Your Department";
		scopeColor = "var(--success-green)";
	} else {
		scopeText = "👤 Viewing: Your Records Only";
		scopeColor = "var(--text-secondary)";
	}

	scopeContainer.innerHTML = `
		<div style="padding: 0.75rem; background: var(--bg-dark-secondary); border-radius: 8px; margin-bottom: 1rem;">
			<span style="color: ${scopeColor}; font-size: 0.875rem; font-weight: 500;">${scopeText}</span>
		</div>
	`;
}

// Display attendance
function displayAttendance(attendance) {
	const listContainer = document.getElementById("attendanceList");

	if (attendance.length === 0) {
		listContainer.innerHTML = `
			<div style="text-align: center; padding: 3rem;">
				<div style="font-size: 3rem; margin-bottom: 1rem;">📋</div>
				<p style="color: var(--text-secondary);">No attendance records found</p>
				<p style="color: var(--text-tertiary); font-size: 0.875rem; margin-top: 0.5rem;">Try adjusting your filters</p>
			</div>
		`;
		return;
	}

	listContainer.innerHTML = "";

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

		// Add visual indicator for invalid or in-progress attendance
		if (!record.is_valid) {
			card.style.borderLeft = "4px solid var(--error-red)";
		} else if (record.status === "in_progress") {
			card.style.borderLeft = "4px solid var(--primary-gold)";
		}

		const date = new Date(record.clock_in_time);
		const dateStr = date.toLocaleDateString("en-US", {
			weekday: "short",
			month: "short",
			day: "numeric",
			year: "numeric",
		});

		const clockInTime = formatTime(record.clock_in_time);
		const clockOutTime = record.clock_out_time
			? formatTime(record.clock_out_time)
			: '<span style="color: var(--primary-gold);">In Progress</span>';
		const timeSpent = record.time_spent_formatted || "--";

		// Build status badges
		let statusBadges = "";
		if (record.status === "in_progress") {
			statusBadges +=
				'<span class="status-badge status-active" style="font-size: 0.75rem; margin-left: 0.5rem;">⏱️ Active</span>';
		}
		if (!record.is_valid) {
			statusBadges +=
				'<span class="status-badge status-past" style="font-size: 0.75rem; margin-left: 0.5rem;">❌ Invalid</span>';
		}

		card.innerHTML = `
            <div class="attendance-card-header">
                <div style="flex: 1;">
                    <div class="service-name-text">${
											record.service_name
										}${statusBadges}</div>
                    ${
											record.service_type
												? `<div style="font-size: 0.75rem; color: var(--text-tertiary); margin-top: 0.25rem;">${record.service_type}</div>`
												: ""
										}
                    ${
											record.user_name &&
											record.user_name !== "undefined undefined"
												? `<div style="font-size: 0.75rem; color: var(--text-secondary); margin-top: 0.25rem;">👤 ${record.user_name}</div>`
												: ""
										}
                </div>
                <div class="attendance-date">${dateStr}</div>
            </div>
            <div class="attendance-card-body">
                ${
									record.location
										? `<div class="attendance-detail">
                    <span class="detail-label">📍 Location:</span>
                    <span class="detail-value">${record.location}</span>
                </div>`
										: ""
								}
                
                <!-- Horizontal Time Details -->
                <div class="attendance-details-row">
                    <div class="attendance-detail-horizontal">
                        <span class="detail-label">🕐 Clock In</span>
                        <span class="detail-value">${clockInTime}</span>
                    </div>
                    <div class="attendance-detail-horizontal">
                        <span class="detail-label">🕑 Clock Out</span>
                        <span class="detail-value">${clockOutTime}</span>
                    </div>
                    <div class="attendance-detail-horizontal">
                        <span class="detail-label">⏱️ Duration</span>
                        <span class="detail-value">${timeSpent}</span>
                    </div>
                </div>
                
                ${
									record.notes
										? `<div class="attendance-detail" style="margin-top: 0.75rem; padding-top: 0.75rem; border-top: 1px solid var(--border-color);">
                    <span class="detail-label">📝 Notes:</span>
                    <span class="detail-value" style="font-size: 0.875rem; display: block; margin-top: 0.25rem;">${record.notes}</span>
                </div>`
										: ""
								}
                ${
									!record.is_valid
										? `<div style="margin-top: 0.75rem; padding: 0.75rem; background-color: rgba(239, 68, 68, 0.1); border-radius: 8px; border-left: 3px solid var(--error-red);">
                    <span style="color: var(--error-red); font-size: 0.875rem; font-weight: 500;">⚠️ Invalid Attendance</span>
                    <p style="color: var(--text-secondary); font-size: 0.75rem; margin-top: 0.25rem;">Less than 30 minutes - does not count toward rewards</p>
                </div>`
										: ""
								}
                ${
									record.status === "in_progress"
										? `<div style="margin-top: 0.75rem; padding: 0.75rem; background-color: rgba(253, 185, 19, 0.1); border-radius: 8px; border-left: 3px solid var(--primary-gold);">
                    <span style="color: var(--primary-gold); font-size: 0.875rem; font-weight: 500;">⏱️ Currently Active</span>
                    <p style="color: var(--text-secondary); font-size: 0.75rem; margin-top: 0.25rem;">Remember to clock out before leaving</p>
                </div>`
										: ""
								}
            </div>
        `;

		listContainer.appendChild(card);
	});
}

// Update pagination controls
function updatePaginationControls(pagination) {
	const paginationContainer = document.getElementById("paginationControls");
	if (!paginationContainer) return;

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

	const prevDisabled = pagination.current_page === 1 ? "disabled" : "";
	const nextDisabled =
		pagination.current_page === pagination.total_pages ? "disabled" : "";

	paginationContainer.innerHTML = `
		<div style="display: flex; justify-content: space-between; align-items: center; margin-top: 1.5rem; padding: 1rem; background: var(--bg-dark-secondary); border-radius: 12px;">
			<button class="btn btn-secondary" onclick="previousPage()" ${prevDisabled}>
				← Previous
			</button>
			<div style="color: var(--text-secondary); font-size: 0.875rem;">
				Page ${pagination.current_page} of ${pagination.total_pages}
				<span style="color: var(--text-tertiary);">(${pagination.total} total)</span>
			</div>
			<button class="btn btn-secondary" onclick="nextPage()" ${nextDisabled}>
				Next →
			</button>
		</div>
	`;
}

// Pagination functions
function previousPage() {
	if (currentPage > 1) {
		currentPage--;
		loadAttendanceHistory();
		window.scrollTo({ top: 0, behavior: "smooth" });
	}
}

function nextPage() {
	if (currentPage < totalPages) {
		currentPage++;
		loadAttendanceHistory();
		window.scrollTo({ top: 0, behavior: "smooth" });
	}
}

// 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";
	}
}
