Files
peworkshop/app/(main)/admin/clues/page.js

1119 lines
31 KiB
JavaScript

"use client";
import { useState, useEffect, useRef } from "react";
import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";
export default function AdminCluesPage() {
const { data: session, status } = useSession();
const [clues, setClues] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
const router = useRouter();
const [isEditMode, setIsEditMode] = useState(false);
const [editingClue, setEditingClue] = useState(null);
const [fixMessage, setFixMessage] = useState("");
// Add a lastRefresh timestamp to track when data was last fetched
const [lastRefresh, setLastRefresh] = useState(Date.now());
// Add next refresh countdown state
const [nextRefresh, setNextRefresh] = useState(10);
// Add auto-refresh enabled/disabled state
const [autoRefreshEnabled, setAutoRefreshEnabled] = useState(true);
// Ref to store interval ID for cleanup
const refreshIntervalRef = useRef(null);
// Form state for adding new clues - add qrCode field back
const [newClue, setNewClue] = useState({
title: "",
description: "",
location: "",
qr_code: "", // Add QR code field
});
const [isReorderMode, setIsReorderMode] = useState(false);
const [reorderingClue, setReorderingClue] = useState(null);
const [newPosition, setNewPosition] = useState(1);
const [reorderMessage, setReorderMessage] = useState("");
// Check if user is admin
useEffect(() => {
if (status === "authenticated") {
if (session?.user?.role !== "admin") {
router.push("/team-selection");
} else {
fetchClues();
}
} else if (status === "unauthenticated") {
router.push("/login");
}
}, [session, status, router]);
// Controlled auto-refresh effect
useEffect(() => {
// Only set up auto-refresh if enabled and not in edit mode
if (autoRefreshEnabled && !isEditMode && status === "authenticated") {
// Clear any existing interval
if (refreshIntervalRef.current) {
clearInterval(refreshIntervalRef.current);
}
// Set initial countdown value
setNextRefresh(10);
// Set up countdown interval
refreshIntervalRef.current = setInterval(() => {
setNextRefresh((prev) => {
// When countdown reaches 0, refresh the data and reset countdown
if (prev <= 1) {
fetchClues();
return 10;
}
return prev - 1;
});
}, 1000);
}
// Clean up interval on unmount or when dependencies change
return () => {
if (refreshIntervalRef.current) {
clearInterval(refreshIntervalRef.current);
}
};
}, [autoRefreshEnabled, isEditMode, status]);
// Disable auto-refresh when entering edit mode
useEffect(() => {
if (isEditMode) {
setAutoRefreshEnabled(false);
}
}, [isEditMode]);
// Fetch all clues
const fetchClues = async () => {
// Skip fetch if in edit mode to prevent data loss
if (isEditMode) {
return;
}
try {
setLoading(true);
// Make sure to get all clues with a high limit to avoid pagination issues
const timestamp = Date.now();
const response = await fetch(
`/api/admin/clues?t=${timestamp}&limit=100`,
{
method: "GET",
headers: {
"Content-Type": "application/json",
"Cache-Control": "no-cache, no-store, must-revalidate",
Pragma: "no-cache",
},
credentials: "include",
}
);
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(
errorData.error || `Failed to fetch clues (${response.status})`
);
}
const data = await response.json();
// Validate the response data
if (!Array.isArray(data)) {
throw new Error("Invalid response format from server");
}
// Sort the clues by ID to ensure correct ordering
const sortedClues = [...data].sort((a, b) => a.id - b.id);
console.log("Fetched clues:", sortedClues);
setClues(sortedClues);
setError("");
// Update lastRefresh timestamp
setLastRefresh(Date.now());
// Reset countdown after manual refresh
setNextRefresh(10);
} catch (err) {
console.error("Error fetching clues:", err);
setError(err.message);
} finally {
setLoading(false);
}
};
// Handle input change for new clue form
const handleInputChange = (e) => {
const { name, value } = e.target;
setNewClue((prev) => ({
...prev,
[name]: value,
}));
};
// Handle form submission to add new clue
const handleAddClue = async (e) => {
e.preventDefault();
try {
setLoading(true);
// Now include the QR code in the request
const response = await fetch("/api/admin/clues", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(newClue),
credentials: "include",
});
const data = await response.json();
if (!response.ok) {
throw new Error(
data.error || `Failed to add clue (Status: ${response.status})`
);
}
// Refresh the clue list with force refresh
await fetchClues();
// Reset the form - now with qrCode
setNewClue({
title: "",
description: "",
location: "",
qr_code: "",
});
setError("");
} catch (err) {
console.error("Error adding clue:", err);
setError(err.message);
} finally {
setLoading(false);
}
};
// Start editing a clue
const handleEditStart = (clue) => {
// Disable auto-refresh when starting to edit
setAutoRefreshEnabled(false);
setEditingClue({
id: clue.id,
title: clue.title,
description: clue.description,
location: clue.location || "",
// Use the actual qr_code from the clue object if available
qr_code: clue.qr_code || `QR${clue.id}`,
});
setIsEditMode(true);
};
// Handle input change for editing clue
const handleEditChange = (e) => {
const { name, value } = e.target;
setEditingClue((prev) => ({
...prev,
[name]: value,
}));
};
// Handle form submission to update clue
const handleUpdateClue = async (e) => {
e.preventDefault();
try {
setLoading(true);
const response = await fetch(`/api/admin/clues/${editingClue.id}`, {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
title: editingClue.title,
description: editingClue.description,
location: editingClue.location,
qr_code: editingClue.qr_code, // Add QR code to the update
}),
credentials: "include",
});
const data = await response.json();
if (!response.ok) {
throw new Error(
data.error || `Failed to update clue (Status: ${response.status})`
);
}
// Refresh the clue list with force refresh
await fetchClues();
setIsEditMode(false);
setEditingClue(null);
setError("");
} catch (err) {
console.error("Error updating clue:", err);
setError(err.message);
} finally {
setLoading(false);
}
};
// Cancel editing
const handleCancelEdit = () => {
setIsEditMode(false);
setEditingClue(null);
// Re-enable auto-refresh when canceling edit
setAutoRefreshEnabled(true);
};
// Force refresh the clue list
const handleForceRefresh = () => {
fetchClues();
};
// Toggle auto-refresh
const toggleAutoRefresh = () => {
setAutoRefreshEnabled((prev) => !prev);
};
// Handle deleting a clue with automatic QR code renumbering
const handleDeleteClue = async (clueId, qrCode) => {
if (
!confirm(
"Are you sure you want to delete this clue?\n\nQR codes will be automatically renumbered to prevent gaps in the sequence."
)
)
return;
try {
setLoading(true);
// QR codes will always be renumbered - no need to pass this parameter anymore
const response = await fetch(`/api/admin/clues/${clueId}`, {
method: "DELETE",
headers: {
"Content-Type": "application/json",
},
credentials: "include",
});
// Parse the response data for detailed error messages
const data = await response.json().catch(() => ({}));
if (!response.ok) {
throw new Error(
data.error || `Failed to delete clue (Status: ${response.status})`
);
}
// Success message and refresh
console.log("Clue deleted successfully:", data.message || "Success");
// Refresh the clue list to show updated QR codes
fetchClues();
setError("");
} catch (err) {
console.error("Error deleting clue:", err);
setError(`Error deleting clue: ${err.message}`);
} finally {
setLoading(false);
}
};
// Start reordering a clue
const handleReorderStart = (clue) => {
// Disable auto-refresh when starting to reorder
setAutoRefreshEnabled(false);
setReorderingClue(clue);
setNewPosition(clue.id); // Default to current position
setIsReorderMode(true);
};
// Handle position selection change
const handlePositionChange = (e) => {
setNewPosition(parseInt(e.target.value));
};
// Cancel reordering
const handleCancelReorder = () => {
setIsReorderMode(false);
setReorderingClue(null);
// Re-enable auto-refresh
setAutoRefreshEnabled(true);
};
// Submit reorder request
const handleReorderSubmit = async (e) => {
e.preventDefault();
if (!reorderingClue || newPosition < 1 || newPosition > clues.length) {
setError("Invalid position selected");
return;
}
try {
setLoading(true);
setReorderMessage("");
// Store reordering info for success message
const clueTitle = reorderingClue.title;
const targetPosition = newPosition;
const response = await fetch("/api/admin/clues/reorder", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
clueId: reorderingClue.id,
newPosition: newPosition,
}),
credentials: "include",
});
const data = await response.json();
if (!response.ok) {
throw new Error(
data.error || `Failed to reorder clue (Status: ${response.status})`
);
}
// Success message
setReorderMessage(
`Clue "${clueTitle}" moved to position ${targetPosition} successfully`
);
// Reset all state to ensure fresh data
setClues([]);
setIsReorderMode(false);
setReorderingClue(null);
setError("");
// Force a complete refresh with delay to allow database to complete operations
setTimeout(async () => {
try {
await fetchClues();
console.log("Clues refreshed after reordering");
} catch (refreshError) {
console.error("Error refreshing clues after reorder:", refreshError);
setError(
"Reordering succeeded but failed to refresh the list. Please reload the page."
);
}
}, 800);
} catch (err) {
console.error("Error reordering clue:", err);
setError(err.message);
setLoading(false);
}
};
// Add a function to force a hard refresh that bypasses cache
const forceHardRefresh = async () => {
try {
setLoading(true);
setClues([]);
// Clear browser cache for this specific request
const timestamp = Date.now();
const response = await fetch(
`/api/admin/clues?t=${timestamp}&forceRefresh=true`,
{
method: "GET",
headers: {
"Content-Type": "application/json",
"Cache-Control": "no-cache, no-store, must-revalidate",
Pragma: "no-cache",
Expires: "0",
},
credentials: "include",
}
);
if (!response.ok) {
throw new Error(`Failed to refresh clues (Status: ${response.status})`);
}
const data = await response.json();
// Sort the clues by ID to ensure correct ordering
const sortedClues = [...data].sort((a, b) => a.id - b.id);
console.log("Force refreshed clues:", sortedClues);
setClues(sortedClues);
setLastRefresh(Date.now());
setNextRefresh(10);
} catch (err) {
console.error("Error during hard refresh:", err);
setError(`Refresh failed: ${err.message}. Try reloading the page.`);
} finally {
setLoading(false);
}
};
if (status === "loading" || loading) {
return <div className="admin-page loading">Loading...</div>;
}
if (status === "unauthenticated") {
return null; // Will redirect via useEffect
}
return (
<div className="admin-page">
<div className="page-header">
<div className="page-title">Manage Clues</div>
<div className="header-controls">
<button
onClick={toggleAutoRefresh}
className={`auto-refresh-toggle ${
autoRefreshEnabled ? "active" : ""
}`}
title={autoRefreshEnabled ? "Auto-refresh on" : "Auto-refresh off"}
>
{autoRefreshEnabled ? "🔄 Auto" : "⏸️ Auto"}
{autoRefreshEnabled && (
<span className="refresh-countdown">{nextRefresh}s</span>
)}
</button>
<button
onClick={handleForceRefresh}
className="refresh-button"
title="Force refresh"
>
🔄
</button>
</div>
</div>
<div className="admin-content">
{error && <p className="error-message">{error}</p>}
{fixMessage && <p className="success-message">{fixMessage}</p>}
{/* Reordering Modal */}
{isReorderMode ? (
<div className="admin-card">
<h2>Change Clue Position</h2>
<form onSubmit={handleReorderSubmit}>
<div className="form-group">
<label htmlFor="clue-position">
Move clue "{reorderingClue?.title}" to new position:
</label>
<select
id="clue-position"
value={newPosition}
onChange={handlePositionChange}
className="admin-input"
>
{clues.map((_, index) => (
<option key={index + 1} value={index + 1}>
{index + 1}
</option>
))}
</select>
<div className="help-text">
This will change the sequence of this clue and update all clue
positions accordingly. QR codes will also be reorganized to
maintain the same sequence.
</div>
</div>
<div className="form-actions">
<button type="submit" className="admin-button">
Change Position
</button>
<button
type="button"
className="admin-button cancel-button"
onClick={handleCancelReorder}
>
Cancel
</button>
</div>
</form>
</div>
) : (
<>
{/* Add New Clue Form */}
{!isEditMode ? (
<div className="admin-card">
<h2>Add New Clue</h2>
<form onSubmit={handleAddClue}>
<div className="form-group">
<label htmlFor="title">Title</label>
<input
type="text"
id="title"
name="title"
value={newClue.title}
onChange={handleInputChange}
required
className="admin-input"
/>
</div>
<div className="form-group">
<label htmlFor="description">Description</label>
<textarea
id="description"
name="description"
value={newClue.description}
onChange={handleInputChange}
required
className="admin-textarea"
></textarea>
</div>
<div className="form-group">
<label htmlFor="location">Location Hint</label>
<input
type="text"
id="location"
name="location"
value={newClue.location}
onChange={handleInputChange}
className="admin-input"
/>
</div>
{/* Add QR code field with new label */}
<div className="form-group">
<label htmlFor="qr_code">QR Answer Value</label>
<input
type="text"
id="qr_code"
name="qr_code"
value={newClue.qr_code}
onChange={handleInputChange}
className="admin-input"
placeholder="QR1, QR2, etc."
/>
<div className="help-text">
QR codes should follow the format QR[number] (e.g., QR1,
QR2). Leave blank to auto-generate.
</div>
</div>
<button type="submit" className="admin-button">
Add Clue
</button>
</form>
</div>
) : (
<div className="admin-card">
<h2>Edit Clue</h2>
<form onSubmit={handleUpdateClue}>
<div className="form-group">
<label htmlFor="edit-title">Title</label>
<input
type="text"
id="edit-title"
name="title"
value={editingClue.title}
onChange={handleEditChange}
required
className="admin-input"
/>
</div>
<div className="form-group">
<label htmlFor="edit-description">Description</label>
<textarea
id="edit-description"
name="description"
value={editingClue.description}
onChange={handleEditChange}
required
className="admin-textarea"
></textarea>
</div>
<div className="form-group">
<label htmlFor="edit-location">Location Hint</label>
<input
type="text"
id="edit-location"
name="location"
value={editingClue.location}
onChange={handleEditChange}
className="admin-input"
/>
</div>
<div className="form-group">
<label htmlFor="edit-qrcode">QR Answer Value</label>
<input
type="text"
id="edit-qrcode"
name="qr_code"
value={editingClue.qr_code}
onChange={handleEditChange}
className="admin-input"
/>
<div className="help-text">
QR codes should follow the format QR[number] (e.g., QR1,
QR2). The QR code value determines what users scan to find
this clue.
</div>
</div>
<div className="form-actions">
<button type="submit" className="admin-button">
Update Clue
</button>
<button
type="button"
className="admin-button cancel-button"
onClick={handleCancelEdit}
>
Cancel
</button>
</div>
</form>
</div>
)}
{/* Existing Clues List */}
<div className="admin-card">
<h2>Existing Clues</h2>
{reorderMessage && (
<p className="success-message">{reorderMessage}</p>
)}
<p className="info-text">
QR codes are the values that users scan to find each clue. You
can customize these values, but they should usually follow the
format QR[number].
</p>
<div className="last-updated">
Last updated: {new Date(lastRefresh).toLocaleTimeString()}
{autoRefreshEnabled && !isEditMode && (
<span> (next refresh in {nextRefresh}s)</span>
)}
</div>
{clues.length === 0 ? (
<p className="no-clues">No clues found.</p>
) : (
<div className="clues-list">
{clues.map((clue) => (
<div key={clue.id} className="clue-item">
<div className="clue-header">
<h3>{clue.title}</h3>
<div className="clue-actions">
<button
className="reorder-button"
onClick={() => handleReorderStart(clue)}
>
Reorder
</button>
<button
className="edit-button"
onClick={() => handleEditStart(clue)}
>
Edit
</button>
<button
className="delete-button"
onClick={() =>
handleDeleteClue(clue.id, clue.qr_code)
}
>
Delete
</button>
</div>
</div>
<p className="clue-description">{clue.description}</p>
{clue.location && (
<p className="clue-location">
<strong>Location:</strong> {clue.location}
</p>
)}
<p className="clue-qr-code">
<strong>QR Code:</strong>{" "}
{clue.qr_code || `QR${clue.id}`}
</p>
</div>
))}
</div>
)}
</div>
</>
)}
</div>
{/* Admin Navigation Bar */}
<div className="admin-nav-bar">
<button
className="admin-nav-button"
onClick={() => router.push("/admin")}
>
<div className="admin-nav-icon">⏱️</div>
<div className="admin-nav-label">Timer</div>
</button>
<button
className="admin-nav-button active"
onClick={() => router.push("/admin/clues")}
>
<div className="admin-nav-icon">📝</div>
<div className="admin-nav-label">Clues</div>
</button>
<button
className="admin-nav-button"
onClick={() => router.push("/admin/leaderboard")}
>
<div className="admin-nav-icon">🏆</div>
<div className="admin-nav-label">Leaderboard</div>
</button>
</div>
<style jsx>{`
.admin-page {
display: flex;
flex-direction: column;
min-height: 100vh;
background-color: #f4e9dc;
}
.page-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem;
background-color: #68543c;
color: white;
}
.page-title {
font-size: 1.2rem;
font-weight: 600;
}
.header-controls {
display: flex;
gap: 10px;
align-items: center;
}
.auto-refresh-toggle {
display: flex;
align-items: center;
gap: 5px;
background-color: #5a4832;
color: white;
border: none;
border-radius: 4px;
padding: 5px 10px;
cursor: pointer;
font-size: 0.9rem;
opacity: 0.8;
}
.auto-refresh-toggle.active {
background-color: #4caf50;
opacity: 1;
}
.refresh-countdown {
font-size: 0.8rem;
background-color: rgba(255, 255, 255, 0.25);
border-radius: 3px;
padding: 0 5px;
margin-left: 3px;
}
.admin-content {
flex: 1;
padding: 1rem;
display: flex;
flex-direction: column;
align-items: center;
padding-bottom: 70px; /* Space for navbar */
}
.admin-card {
width: 100%;
max-width: 700px;
background-color: white;
border-radius: 8px;
padding: 1.5rem;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
margin-bottom: 2rem;
}
.form-group {
margin-bottom: 1rem;
}
.form-row {
display: flex;
gap: 1rem;
}
.half {
flex: 1;
}
.admin-input {
width: 100%;
padding: 0.6rem;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 1rem;
}
.admin-textarea {
width: 100%;
padding: 0.6rem;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 1rem;
min-height: 100px;
resize: vertical;
}
label {
display: block;
margin-bottom: 0.4rem;
font-weight: 500;
}
.admin-button {
background-color: #68543c;
color: white;
border: none;
border-radius: 4px;
padding: 0.75rem 1rem;
font-size: 1rem;
cursor: pointer;
margin-top: 0.5rem;
}
.clues-list {
display: flex;
flex-direction: column;
gap: 1rem;
}
.clue-item {
border: 1px solid #ddd;
border-radius: 4px;
padding: 1rem;
background-color: #f9f9f9;
}
.clue-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 0.5rem;
}
.clue-header h3 {
margin: 0;
font-size: 1.1rem;
}
.delete-button {
background-color: #d32f2f;
color: white;
border: none;
border-radius: 4px;
padding: 0.4rem 0.6rem;
font-size: 0.9rem;
cursor: pointer;
}
.clue-description {
margin-bottom: 0.8rem;
}
.clue-location,
.clue-position {
font-size: 0.9rem;
margin-bottom: 0.4rem;
}
.clue-qr-code {
font-size: 0.9rem;
margin-bottom: 0.4rem;
}
.error-message {
color: red;
margin-bottom: 1rem;
padding: 0.5rem;
border-radius: 4px;
background-color: #ffebee;
width: 100%;
max-width: 700px;
text-align: center;
}
.no-clues {
text-align: center;
color: #666;
padding: 2rem 0;
}
/* Admin Navigation Bar Styles */
.admin-nav-bar {
display: flex;
justify-content: space-around;
background-color: white;
border-top: 1px solid #ddd;
padding: 10px 0;
position: fixed;
bottom: 0;
left: 0;
width: 100%;
box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
z-index: 100;
}
.admin-nav-button {
display: flex;
flex-direction: column;
align-items: center;
background: transparent;
border: none;
padding: 8px 0;
flex: 1;
cursor: pointer;
color: #666;
transition: all 0.2s ease;
}
.admin-nav-button.active {
color: #68543c;
font-weight: bold;
}
.admin-nav-button:hover {
background-color: rgba(104, 84, 60, 0.1);
}
.admin-nav-icon {
font-size: 24px;
margin-bottom: 4px;
}
.admin-nav-label {
font-size: 13px;
}
.help-text {
font-size: 0.8rem;
color: #666;
margin-top: 4px;
}
.form-actions {
display: flex;
gap: 1rem;
margin-top: 1rem;
}
.cancel-button {
background-color: #757575;
}
.edit-button {
background-color: #2196f3;
color: white;
border: none;
border-radius: 4px;
padding: 0.4rem 0.6rem;
font-size: 0.9rem;
cursor: pointer;
margin-right: 8px;
}
.clue-actions {
display: flex;
gap: 0.5rem;
}
.admin-input.disabled {
background-color: #f5f5f5;
color: #666;
}
.admin-tools {
display: none;
}
.tool-button,
.sequence-button,
.fix-button {
display: none;
}
.tool-description {
display: none;
}
.success-message {
color: #4caf50;
margin-bottom: 1rem;
padding: 0.5rem;
border-radius: 4px;
background-color: #e8f5e9;
width: 100%;
max-width: 700px;
text-align: center;
}
.info-text {
font-size: 0.9rem;
color: #666;
margin-bottom: 1rem;
padding: 0.5rem;
background-color: #f5f5f5;
border-left: 3px solid #2196f3;
}
.refresh-button {
background: transparent;
border: none;
font-size: 1.2rem;
cursor: pointer;
padding: 0.5rem;
margin-left: 1rem;
color: white;
}
.refresh-button:hover {
transform: rotate(90deg);
transition: transform 0.3s ease;
}
.last-updated {
font-size: 0.8rem;
color: #666;
margin-bottom: 1rem;
text-align: right;
font-style: italic;
}
.reorder-button {
background-color: #9c27b0;
color: white;
border: none;
border-radius: 4px;
padding: 0.4rem 0.6rem;
cursor: pointer;
font-size: 0.9rem;
margin-right: 8px;
}
.reorder-button:hover {
background-color: #7b1fa2;
}
`}</style>
</div>
);
}