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 allTickets = [];
let filteredTickets = [];
let allUsers = [];
let currentPage = 1;
const itemsPerPage = 20;

// Initialize
document.addEventListener("DOMContentLoaded", () => {
	//loadAdminProfile();
	loadTicketsStats();
	loadUsers();
	loadTickets();

	// Event listeners
	document
		.getElementById("searchInput")
		.addEventListener("input", filterTickets);
	document
		.getElementById("statusFilter")
		.addEventListener("change", filterTickets);
	document
		.getElementById("issueUserId")
		.addEventListener("change", filterTickets);
});

// Load tickets statistics
async function loadTicketsStats() {
	try {
		const response = await apiRequest(API_ENDPOINTS.TICKET_STATS);
		const stats = await response.data;
		console.log(stats);

		document.getElementById("totalTickets").textContent =
			stats.total_tickets || 0;
		document.getElementById("unresolvedTickets").textContent =
			stats.unresolved_tickets || 0;
		document.getElementById("resolvedTickets").textContent =
			stats.resolved_tickets || 0;
		document.getElementById("affectedUsers").textContent =
			stats.affected_users || 0;
	} catch (error) {
		console.error("Failed to load tickets stats:", error);
	}
}

// Load users for dropdown
async function loadUsers() {
	try {
		const response = await apiRequest(API_ENDPOINTS.USERS_LIST);
		allUsers = response.data.users || [];

		const select = document.getElementById("issueUserId");
		allUsers.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 all tickets
async function loadTickets() {
	try {
		const response = await apiRequest(API_ENDPOINTS.TICKETS_LIST);
		allTickets = response.data.tickets || [];
		filteredTickets = [...allTickets];

		displayTickets();
	} catch (error) {
		console.error("Failed to load tickets:", error);
		showMessage("Failed to load tickets", "error");
		document.getElementById("ticketsTableBody").innerHTML =
			'<tr><td colspan="8" style="text-align: center; padding: 40px;">Failed to load tickets</td></tr>';
	}
}

// Filter tickets
function filterTickets() {
	const searchTerm = document.getElementById("searchInput").value.toLowerCase();
	const statusFilter = document.getElementById("statusFilter").value;
	const issueUserId = document.getElementById("issueUserId").value;

	filteredTickets = allTickets.filter((ticket) => {
		const matchesSearch =
			ticket.user_name.toLowerCase().includes(searchTerm) ||
			ticket.issued_by_name.toLowerCase().includes(searchTerm) ||
			ticket.reason.toLowerCase().includes(searchTerm);

		const matchesStatus =
			!statusFilter ||
			(statusFilter === "unresolved" && !ticket.is_resolved) ||
			(statusFilter === "resolved" && ticket.is_resolved);

		const matchesUser = !issueUserId || ticket.issued_by_id == issueUserId;

		return matchesSearch && matchesStatus && matchesUser;
	});

	currentPage = 1;
	displayTickets();
}

// Display tickets
function displayTickets() {
	const tbody = document.getElementById("ticketsTableBody");

	if (filteredTickets.length === 0) {
		tbody.innerHTML =
			'<tr><td colspan="8" style="text-align: center; padding: 40px;">No penalty tickets found</td></tr>';
		document.getElementById("pagination").innerHTML = "";
		return;
	}

	const startIndex = (currentPage - 1) * itemsPerPage;
	const endIndex = startIndex + itemsPerPage;
	const pageTickets = filteredTickets.slice(startIndex, endIndex);

	tbody.innerHTML = "";

	pageTickets.forEach((ticket) => {
		const row = document.createElement("tr");

		const issuedDate = formatDateTime(ticket.issued_at);
		const resolvedDate = ticket.resolved_at
			? formatDateTime(ticket.resolved_at)
			: "--";

		const statusBadge = ticket.is_resolved
			? '<span class="status-badge status-active">Resolved</span>'
			: '<span class="status-badge status-past">Unresolved</span>';

		const reasonPreview =
			ticket.reason.length > 50
				? ticket.reason.substring(0, 50) + "..."
				: ticket.reason;

		row.innerHTML = `
			<td>#${ticket.id}</td>
			<td>${ticket.user_name}</td>
			<td>${reasonPreview}</td>
			<td>${ticket.issued_by_name}</td>
			<td>${issuedDate}</td>
			<td>${statusBadge}</td>
			<td>${resolvedDate}</td>
			<td>
				<div class="action-buttons">
					<button class="btn-icon" onclick="viewTicket(${
						ticket.id
					})" title="View Details">
						<svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24">
							<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
							<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path>
						</svg>
					</button>
					${
						!ticket.is_resolved
							? `
						<button class="btn-icon btn-success" onclick="openResolveModal(${ticket.id}, '${
									ticket.user_name
							  }', '${ticket.reason.replace(
									/'/g,
									"\\'"
							  )}'))" title="Resolve Ticket">
							<svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24">
								<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
							</svg>
						</button>
					`
							: ""
					}
				</div>
			</td>
		`;

		tbody.appendChild(row);
	});

	renderPagination();
}

// Render pagination
function renderPagination() {
	const totalPages = Math.ceil(filteredTickets.length / itemsPerPage);
	const paginationContainer = document.getElementById("pagination");

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

	let html = "";

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

	// Page numbers
	for (let i = 1; i <= totalPages; i++) {
		if (
			i === 1 ||
			i === totalPages ||
			(i >= currentPage - 2 && i <= currentPage + 2)
		) {
			html += `<button class="pagination-btn ${
				i === currentPage ? "active" : ""
			}" onclick="changePage(${i})">${i}</button>`;
		} else if (i === currentPage - 3 || i === currentPage + 3) {
			html += `<span class="pagination-ellipsis">...</span>`;
		}
	}

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

	paginationContainer.innerHTML = html;
}

// Change page
function changePage(page) {
	currentPage = page;
	displayTickets();
}

// View Ticket
function viewTicket(ticketId) {
	const ticket = allTickets.find((t) => t.id === ticketId);
	if (!ticket) return;

	document.getElementById("viewTicketId").value = `#${ticket.id}`;
	document.getElementById("viewUserName").value = ticket.user_name;
	document.getElementById("viewIssuedBy").value = ticket.issued_by_name;
	document.getElementById("viewReason").value = ticket.reason;
	document.getElementById("viewIssuedDate").value = formatDateTime(
		ticket.issued_at
	);
	document.getElementById("viewStatus").value = ticket.is_resolved
		? "Resolved"
		: "Unresolved";

	if (ticket.is_resolved && ticket.resolved_at) {
		document.getElementById("viewResolvedDateGroup").style.display = "block";
		document.getElementById("viewResolvedDate").value = formatDateTime(
			ticket.resolved_at
		);
	} else {
		document.getElementById("viewResolvedDateGroup").style.display = "none";
	}

	document.getElementById("viewModal").classList.add("active");
}

// Close View Modal
function closeViewModal() {
	document.getElementById("viewModal").classList.remove("active");
}

// Open Resolve Modal
function openResolveModal(ticketId, userName, reason) {
	document.getElementById("resolveTicketId").value = `#${ticketId}`;
	document.getElementById("resolveUserName").value = userName;
	document.getElementById("resolveReason").value = reason;
	document
		.getElementById("resolveModal")
		.setAttribute("data-ticket-id", ticketId);
	document.getElementById("resolveModal").classList.add("active");
}

// Close Resolve Modal
function closeResolveModal() {
	document.getElementById("resolveModal").classList.remove("active");
}

// Confirm Resolve
async function confirmResolve() {
	const modal = document.getElementById("resolveModal");
	const ticketId = modal.getAttribute("data-ticket-id");

	try {
		await apiRequest(API_ENDPOINTS.TICKETS_LIST, {
			method: "PUT",
			body: JSON.stringify({ ticket_id: ticketId, is_resolved: true }),
		});

		showMessage("Penalty ticket resolved successfully", "success");
		closeResolveModal();
		loadTicketsStats();
		loadTickets();
	} catch (error) {
		console.error("Failed to resolve ticket:", error);
		showMessage(error.message || "Failed to resolve penalty ticket", "error");
	}
}

// Open Issue Modal
function openIssueModal() {
	document.getElementById("issueUserId").value = "";
	document.getElementById("issueReason").value = "";
	document.getElementById("issueModal").classList.add("active");
}

// Close Issue Modal
function closeIssueModal() {
	document.getElementById("issueModal").classList.remove("active");
}

// Confirm Issue
async function confirmIssue() {
	const userId = document.getElementById("issueUserId").value;
	const reason = document.getElementById("issueReason").value.trim();

	if (!userId) {
		showMessage("Please select a user", "error");
		return;
	}

	if (!reason) {
		showMessage("Please provide a reason for the penalty", "error");
		return;
	}

	try {
		await apiRequest(API_ENDPOINTS.TICKETS_LIST, {
			method: "POST",
			body: JSON.stringify({ user_id: userId, reason }),
		});

		showMessage("Penalty ticket issued successfully", "success");
		closeIssueModal();
		loadTicketsStats();
		loadTickets();
	} catch (error) {
		console.error("Failed to issue ticket:", error);
		showMessage(error.message || "Failed to issue penalty ticket", "error");
	}
}

// Export tickets
function exportTickets() {
	const csv = convertToCSV(filteredTickets);
	downloadCSV(
		csv,
		`penalty_tickets_export_${new Date().toISOString().split("T")[0]}.csv`
	);
	showMessage("Penalty tickets exported successfully", "success");
}

// Convert to CSV
function convertToCSV(data) {
	const headers = [
		"Ticket ID",
		"User",
		"Reason",
		"Issued By",
		"Issued Date",
		"Status",
		"Resolved Date",
	];
	const rows = data.map((ticket) => [
		ticket.id,
		ticket.user_name,
		`"${ticket.reason.replace(/"/g, '""')}"`,
		ticket.issued_by_name,
		formatDateTime(ticket.issued_at),
		ticket.is_resolved ? "Resolved" : "Unresolved",
		ticket.resolved_at ? formatDateTime(ticket.resolved_at) : "--",
	]);

	return [headers, ...rows].map((row) => row.join(",")).join("\n");
}

// Download CSV
function downloadCSV(csv, filename) {
	const blob = new Blob([csv], { type: "text/csv" });
	const url = window.URL.createObjectURL(blob);
	const a = document.createElement("a");
	a.href = url;
	a.download = filename;
	a.click();
	window.URL.revokeObjectURL(url);
}

// Utility functions
function requireAuth() {
	// Implementation for checking authentication
}

function getUserData() {
	// Implementation for fetching user data
}

async function apiRequest(endpoint, options = {}) {
	// Implementation for API request
}

function formatDate(date) {
	// Implementation for date formatting
}

function formatDateTime(date) {
	// Implementation for date and time formatting
}

function showMessage(message, type) {
	// Implementation for showing messages
}
