Files
peworkshop/app/(main)/admin/page.js
T
2025-03-11 17:21:46 +00:00

99 lines
3.1 KiB
JavaScript

'use client'; // Mark as a Client Component
import { useState, useEffect } from 'react';
import { useSession } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import { startHuntTimer, getHuntStatus } from '../actions/auth';
export default function Admin() {
const { data: session, status } = useSession();
const [timerActive, setTimerActive] = useState(false);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
const router = useRouter();
// Load timer status on page load
useEffect(() => {
async function loadTimerStatus() {
try {
const status = await getHuntStatus();
setTimerActive(status.active);
} catch (err) {
console.error('Failed to load timer status:', err);
setError('Failed to load timer status');
} finally {
setLoading(false);
}
}
if (status === 'authenticated') {
loadTimerStatus();
}
}, [status]);
// Check if user is admin
useEffect(() => {
if (status === 'authenticated' && session?.user?.role !== 'admin') {
router.push('/');
}
}, [session, status, router]);
// Handle access denied and loading states
if (status === 'loading' || loading) {
return <div className="admin-page loading">Loading...</div>;
}
if (status === 'unauthenticated') {
router.push('/login');
return null;
}
if (session?.user?.role !== 'admin') {
return null; // Already redirecting via useEffect
}
const toggleTimer = async () => {
setLoading(true);
try {
const newStatus = !timerActive;
const result = await startHuntTimer(newStatus);
if (result.success) {
setTimerActive(newStatus);
} else {
setError('Failed to update timer status');
}
} catch (err) {
console.error('Failed to toggle timer:', err);
setError('Failed to toggle timer');
} finally {
setLoading(false);
}
};
return (
<div className="admin-page">
<div className="admin-card">
<h1>Admin Controls</h1>
<div className="timer-section">
<h2>Hunt Timer</h2>
<p>Status: <span className={timerActive ? 'active' : 'inactive'}>
{timerActive ? 'Active' : 'Inactive'}
</span></p>
<div className="control-buttons">
<button
onClick={toggleTimer}
className={timerActive ? 'stop-button' : 'start-button'}
disabled={loading}
>
{loading ? 'Updating...' : timerActive ? 'Stop Timer' : 'Start Timer'}
</button>
</div>
</div>
{error && <p className="error">{error}</p>}
</div>
</div>
);
}