import { useEffect, useState } from 'react';
import { api } from '../api';

export default function SimulationList({ refreshTrigger, onSelect }) {
    const [simulations, setSimulations] = useState([]);
    const [error, setError] = useState(null);

    useEffect(() => {
        loadSimulations();
    }, [refreshTrigger]);

    const loadSimulations = async () => {
        try {
            const data = await api.getSimulations();
            console.log('Simulations loaded:', data);
            setSimulations(data);
            setError(null);
        } catch (err) {
            console.error('Error loading simulations:', err);
            setError(err.message);
        }
    };

    const getStatusClass = (status) => {
        switch (status) {
            case 'completed': return 'status-completed';
            case 'running': return 'status-running';
            case 'failed': return 'status-failed';
            default: return 'status-pending';
        }
    };

    return (
        <div className="simulation-list">
            <h2>Simulations récentes</h2>
            {error && <div className="error">Erreur: {error}</div>}
            {simulations.length === 0 && !error && <p>Aucune simulation pour le moment.</p>}
            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Nom</th>
                        <th>Status</th>
                        <th>Créée</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    {simulations.map(sim => (
                        <tr key={sim.id} onClick={() => onSelect(sim)}>
                            <td>#{sim.id}</td>
                            <td>{sim.name}</td>
                            <td>
                                <span className={`status ${getStatusClass(sim.status)}`}>
                                    {sim.status}
                                </span>
                            </td>
                            <td>{new Date(sim.created_at).toLocaleString()}</td>
                            <td>
                                {sim.status === 'completed' && 'Voir résultats'}
                            </td>
                        </tr>
                    ))}
                </tbody>
            </table>
        </div>
    );
}