import React, { useState, useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import { useToast } from '../components/Toast';
import api from '../api/axios';
import { formatLocalDate } from '../utils/dateUtils';
function History() {
const { isAuthenticated } = useAuth();
const { error, success } = useToast();
const navigate = useNavigate();
const [sessions, setSessions] = useState([]);
const [loading, setLoading] = useState(true);
const [closingSession, setClosingSession] = useState(null);
const [showAllSessions, setShowAllSessions] = useState(false);
const loadSessions = useCallback(async () => {
try {
const response = await api.get('/sessions');
setSessions(response.data);
} catch (err) {
console.error('Failed to load sessions', err);
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
loadSessions();
}, [loadSessions]);
useEffect(() => {
const interval = setInterval(() => {
loadSessions();
}, 3000);
return () => clearInterval(interval);
}, [loadSessions]);
const handleCloseSession = async (sessionId, notes) => {
try {
await api.post(`/sessions/${sessionId}/close`, { notes });
await loadSessions();
setClosingSession(null);
success('Session ended successfully');
} catch (err) {
error('Failed to close session');
}
};
if (loading) {
return (
);
}
return (
Session History
Sessions
{sessions.length > 5 && (
)}
{sessions.length === 0 ? (
No sessions found
) : (
{(showAllSessions ? sessions : sessions.slice(0, 5)).map(session => (
navigate(`/history/${session.id}`)}
className="p-4"
>
Session #{session.id}
{session.is_active === 1 && (
Active
)}
{session.games_played} game{session.games_played !== 1 ? 's' : ''}
{formatLocalDate(session.created_at)}
{session.has_notes && session.notes_preview && (
{session.notes_preview}
)}
{isAuthenticated && session.is_active === 1 && (
)}
))}
)}
{closingSession && (
setClosingSession(null)}
onConfirm={handleCloseSession}
/>
)}
);
}
function EndSessionModal({ sessionId, onClose, onConfirm }) {
const [notes, setNotes] = useState('');
return (
End Session #{sessionId}
);
}
export default History;