// App.tsx
import React, { useState } from 'react';
import { MsalProvider } from '@azure/msal-react';
import { msalInstance } from './msalConfig';
import { AuthProvider, useAuth } from './AuthContext';
import type { EvaluationRecord } from './types';
import LoginPage from './LoginPage';
import HistoriquePage from './HistoriquePage';
import SaisiePage from './SaisiePage';
import './styles.css';

const initialRecords: EvaluationRecord[] = [
    {
        id: 1,
        nom: 'Dupont',
        prenom: 'Marie',
        formation: 'BTS NDRC 1 JV',
        autoEvaluation: 'OUI',
        dateAction: '25/01/2026',
        commentaireFormateur: 'Relance HP',
        evaluationTuteur: 'OUI',
        dateActionTuteur: '25/01/2026',
        commentaireRRE: 'Relance Tuteur',
        campus: 'CGY'
    }
];

const AppContent: React.FC = () => {
    const { user, login, logout, isAuthenticated } = useAuth();
    const [currentPage, setCurrentPage] = useState('historique');
    const [records, setRecords] = useState<EvaluationRecord[]>(initialRecords);

    const handleNewEntry = () => {
        setCurrentPage('saisie');
    };

    const handleSave = (newRecord: EvaluationRecord) => {
        setRecords(prev => [...prev, newRecord]);
        setCurrentPage('historique');
    };

    const handleUpdateRecord = (updatedRecord: EvaluationRecord) => {
        setRecords(prev =>
            prev.map(record =>
                record.id === updatedRecord.id ? updatedRecord : record
            )
        );
    };

    const handleCancel = () => {
        setCurrentPage('historique');
    };

    // Si pas authentifié, afficher la page de login
    if (!isAuthenticated || !user) {
        return <LoginPage onLogin={login} />;
    }

    // Si sur la page de saisie
    if (currentPage === 'saisie') {
        return <SaisiePage onSave={handleSave} onCancel={handleCancel} user={user} />;
    }

    // Page historique par défaut
    return (
        <HistoriquePage
            records={records}
            onNewEntry={handleNewEntry}
            onLogout={logout}
            onUpdateRecord={handleUpdateRecord}
            user={user}
           
        />
    );
};

const App: React.FC = () => {
    return (
        <MsalProvider instance={msalInstance}>
            <AuthProvider>
                <AppContent />
            </AuthProvider>
        </MsalProvider>
    );
};

export default App;