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

433 lines
11 KiB
JavaScript

"use client";
import { useState, useEffect, useRef } from "react";
import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";
export default function AdminDashboard() {
const { data: session, status } = useSession();
const [timerActive, setTimerActive] = useState(false);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
const [elapsedTime, setElapsedTime] = useState(0); // in seconds
const [timerDisplay, setTimerDisplay] = useState("--:--:--");
const [presetHours, setPresetHours] = useState("");
const [presetMinutes, setPresetMinutes] = useState("");
const [presetSeconds, setPresetSeconds] = useState("");
const [timerEndTime, setTimerEndTime] = useState(null);
const timerRef = useRef(null);
const router = useRouter();
// Load timer status on page load
useEffect(() => {
async function loadTimerStatus() {
try {
const response = await fetch("/api/hunt/timer", {
credentials: "include",
headers: {
"Cache-Control": "no-cache",
},
});
const data = await response.json();
if (data.active) {
setTimerActive(true);
// Calculate elapsed time
if (data.startTime) {
const startTime = new Date(data.startTime).getTime();
const currentTime = Date.now();
const elapsed = Math.floor((currentTime - startTime) / 1000);
setElapsedTime(elapsed);
}
// If there's an end time, set it
if (data.endTime) {
setTimerEndTime(new Date(data.endTime).getTime());
}
}
setLoading(false);
} catch (err) {
console.error("Failed to load timer status:", err);
setError("Failed to load timer status");
setLoading(false);
}
}
if (status === "authenticated") {
loadTimerStatus();
}
}, [status]);
// Check if user is admin
useEffect(() => {
if (status === "authenticated") {
if (session?.user?.role !== "admin") {
router.push("/team-selection");
}
} else if (status === "unauthenticated") {
router.push("/login");
}
}, [session, status, router]);
// Timer update effect
useEffect(() => {
if (timerActive) {
timerRef.current = setInterval(() => {
setElapsedTime((prev) => {
const newElapsed = prev + 1;
// If we have an end time and we've reached it, stop the timer
if (timerEndTime && Date.now() >= timerEndTime) {
stopTimer();
return prev;
}
// Update the display
formatTimeDisplay(newElapsed);
return newElapsed;
});
}, 1000);
} else {
if (timerRef.current) {
clearInterval(timerRef.current);
}
}
return () => {
if (timerRef.current) {
clearInterval(timerRef.current);
}
};
}, [timerActive, timerEndTime]);
// Format time for display whenever elapsed time changes
useEffect(() => {
formatTimeDisplay(elapsedTime);
}, [elapsedTime]);
// Format seconds into HH:MM:SS
const formatTimeDisplay = (totalSeconds) => {
if (!timerActive) {
setTimerDisplay("--:--:--");
return;
}
const hours = Math.floor(totalSeconds / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const seconds = totalSeconds % 60;
const display = [
hours.toString().padStart(2, "0"),
minutes.toString().padStart(2, "0"),
seconds.toString().padStart(2, "0"),
].join(":");
setTimerDisplay(display);
};
const startTimer = async (preset = false) => {
setLoading(true);
try {
let endTime = null;
// If using preset, calculate the end time
if (preset) {
const hours = parseInt(presetHours || "0");
const minutes = parseInt(presetMinutes || "0");
const seconds = parseInt(presetSeconds || "0");
// Validate input
if (isNaN(hours) || isNaN(minutes) || isNaN(seconds)) {
setError(
"Please enter valid numbers for hours, minutes, and seconds"
);
setLoading(false);
return;
}
// Calculate total duration in milliseconds
const durationMs = (hours * 3600 + minutes * 60 + seconds) * 1000;
if (durationMs <= 0) {
setError("Please enter a duration greater than zero");
setLoading(false);
return;
}
// Set end time
endTime = new Date(Date.now() + durationMs).toISOString();
}
// API call to start timer
const response = await fetch("/api/hunt/timer", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
action: "start",
endTime: endTime,
}),
});
const data = await response.json();
if (data.success) {
setTimerActive(true);
setElapsedTime(0);
if (endTime) {
setTimerEndTime(new Date(endTime).getTime());
} else {
setTimerEndTime(null);
}
setError("");
} else {
setError(data.error || "Failed to start timer");
}
} catch (err) {
console.error("Failed to start timer:", err);
setError("Failed to start timer");
} finally {
setLoading(false);
}
};
const stopTimer = async () => {
setLoading(true);
try {
const response = await fetch("/api/hunt/timer", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ action: "stop" }),
});
const data = await response.json();
if (data.success) {
setTimerActive(false);
setTimerEndTime(null);
setError("");
} else {
setError(data.error || "Failed to stop timer");
}
} catch (err) {
console.error("Failed to stop timer:", err);
setError("Failed to stop timer");
} finally {
setLoading(false);
}
};
const startPresetTimer = () => {
startTimer(true);
};
// Handle access denied and loading states
if (status === "loading" || loading) {
return <div className="admin-page loading">Loading...</div>;
}
if (status === "unauthenticated") {
return null; // Will redirect via useEffect
}
if (session?.user?.role !== "admin") {
return null; // Will redirect via useEffect
}
return (
<div className="admin-page">
<div className="page-header">
<div className="page-title">Admin Dashboard</div>
<div className="placeholder"></div>
</div>
<div className="admin-content">
<div className="timer-display-container">
<h2>Hunt Timer</h2>
<div className="timer-display">{timerDisplay}</div>
<div className="timer-controls">
<button
className="admin-button"
onClick={stopTimer}
disabled={!timerActive || loading}
>
Stop Timer
</button>
<button
className="admin-button"
onClick={() => startTimer(false)}
disabled={timerActive || loading}
>
Start Timer
</button>
</div>
<div className="preset-timer-container">
<h3>Set Timer Duration</h3>
<div className="preset-inputs">
<div className="time-input">
<label>Hours</label>
<input
type="number"
min="0"
value={presetHours}
onChange={(e) => setPresetHours(e.target.value)}
disabled={timerActive || loading}
className="admin-input"
/>
</div>
<div className="time-input">
<label>Minutes</label>
<input
type="number"
min="0"
max="59"
value={presetMinutes}
onChange={(e) => setPresetMinutes(e.target.value)}
disabled={timerActive || loading}
className="admin-input"
/>
</div>
<div className="time-input">
<label>Seconds</label>
<input
type="number"
min="0"
max="59"
value={presetSeconds}
onChange={(e) => setPresetSeconds(e.target.value)}
disabled={timerActive || loading}
className="admin-input"
/>
</div>
</div>
<button
className="admin-button"
onClick={startPresetTimer}
disabled={timerActive || loading}
>
Start Preset Timer
</button>
</div>
{error && <p className="error-message">{error}</p>}
</div>
</div>
<style jsx>{`
.admin-page {
display: flex;
flex-direction: column;
min-height: 100vh;
background-color: #f4e9dc;
}
.page-header {
display: flex;
justify-content: center;
align-items: center;
padding: 1rem;
background-color: #68543c;
color: white;
}
.page-title {
font-size: 1.2rem;
font-weight: 600;
}
.placeholder {
width: 40px;
display: none;
}
.admin-content {
flex: 1;
padding: 1rem;
display: flex;
flex-direction: column;
align-items: center;
}
.timer-display-container {
width: 100%;
max-width: 500px;
background-color: white;
border-radius: 8px;
padding: 2rem;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
text-align: center;
}
.timer-display {
font-size: 3rem;
font-weight: 700;
font-family: monospace;
padding: 1.5rem 0;
}
.timer-controls {
display: flex;
gap: 1rem;
margin-bottom: 2rem;
}
.admin-button {
background-color: #68543c;
color: white;
border: none;
border-radius: 4px;
padding: 0.75rem 1rem;
font-size: 1rem;
cursor: pointer;
flex: 1;
}
.admin-button:disabled {
background-color: #d0c8c0;
cursor: not-allowed;
}
.preset-timer-container {
margin-top: 1.5rem;
padding-top: 1.5rem;
border-top: 1px solid #eee;
}
.preset-inputs {
display: flex;
justify-content: space-between;
gap: 1rem;
margin-bottom: 1rem;
}
.time-input {
flex: 1;
display: flex;
flex-direction: column;
}
.admin-input {
padding: 0.5rem;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 1rem;
text-align: center;
}
.error-message {
color: red;
margin-top: 1rem;
}
`}</style>
</div>
);
}