import React, { useState, useEffect } from 'react';
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
import Header from './components/Header';
import AdminLogin from './components/AdminLogin';
import AdminDashboard from './components/AdminDashboard';
import PublicSearch from './components/PublicSearch';
import './App.css';

const App = () => {
  const [results, setResults] = useState([]);
  const [isAdmin, setIsAdmin] = useState(false);

  useEffect(() => {
    const savedResults = localStorage.getItem('results');
    if (savedResults) {
      setResults(JSON.parse(savedResults));
    }
  }, []);

  const handleSubmit = (data) => {
    const newResults = [...results, data];
    setResults(newResults);
    localStorage.setItem('results', JSON.stringify(newResults));
  };

  const handleDelete = (rollNo) => {
    const newResults = results.filter(r => r.rollNo !== rollNo);
    setResults(newResults);
    localStorage.setItem('results', JSON.stringify(newResults));
  };

  return (
    <Router>
      <div className="app">
        <Header />
        <main className="main-content">
          <Routes>
            <Route path="/" element={<PublicSearch results={results} />} />
            <Route 
              path="/admin" 
              element={
                isAdmin ? (
                  <AdminDashboard
                    results={results}
                    onSubmit={handleSubmit}
                    onDelete={handleDelete}
                    onLogout={() => setIsAdmin(false)}
                  />
                ) : (
                  <AdminLogin onLogin={() => setIsAdmin(true)} />
                )
              } 
            />
            <Route path="*" element={<Navigate to="/" />} />
          </Routes>
        </main>
      </div>
    </Router>
  );
};

export default App;