import React, { useState } from 'react';
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
import { AuthProvider, useAuth } from './contexts/AuthContext';
// import ProtectedRoute from './components/ProtectedRoute';
import Login from './components/Users/Login';
import Main from './components/Main';
import ReportEditor from './components/ReportEditor/ReportEditor';
import UserManager from './components/Users/UserManager';
import './App.css';
import { NomenclatureProvider } from './contexts/NomenclatureContext';
import { NomenclatureDataProvider } from './contexts/NomenclatureDataContext';

// function MainApp() {
//   const [selectedPort, setSelectedPort] = useState(null);
//   const { readings, isConnected, error } = useSerialData();

//   const filteredReadings = selectedPort
//     ? readings.filter(r => r.port === selectedPort)
//     : readings;

//   return (
//     <div className="App">
//       <Header />

//       <div className="status-bar">
//         {isConnected ? (
//           <span className="status-connected">● Connected to Serial Bridge</span>
//         ) : (
//           <span className="status-disconnected">● Disconnected</span>
//         )}
//         {error && (
//           <span className="status-error">{error}</span>
//         )}
//       </div>

//       <div className="container">
//         <DataDisplay readings={filteredReadings} selectedPort={selectedPort} />
//       </div>
//     </div>
//   );
// }

function AppContent() {
  const { user, currentUser, login, logout, loading, isAuthenticated } = useAuth();

  if (loading) {
    return (
      <div className="loading">
        <p>Loading...</p>
      </div>
    );
  }

  if (!isAuthenticated) {
    return <Login onLogin={login} />;
  }

  return (
    <NomenclatureProvider>
      <NomenclatureDataProvider>
        <Routes>
          <Route path="/" element={<Main />} />
          <Route path="/report-editor" element={currentUser?.can_edit_documents ? <ReportEditor /> : <Navigate to="/" />} />
          <Route path="/users" element={currentUser?.is_admin ? <UserManager /> : <Navigate to="/" />} />
        </Routes>
      </NomenclatureDataProvider>
    </NomenclatureProvider>
  );
}


function App() {
  return (
    <Router>
      <AuthProvider>
        <AppContent />
      </AuthProvider>
    </Router>
  );
}

export default App;
