import React, { useState, useEffect } from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import { AuthProvider, useAuth } from './contexts/AuthContext';
import Navbar from './components/Navbar';
import Footer from './components/Footer';
import AuthModal from './components/AuthModal';
import AlphaGate from './components/AlphaGate';
import Home from './pages/Home';
import GoogleCallback from './pages/GoogleCallback';
import VerifyEmail from './pages/VerifyEmail';
import ResetPassword from './pages/ResetPassword';
import ItemList from './pages/ItemList';
import ItemDetail from './pages/ItemDetail';
import EditItem from './pages/EditItem';
import RentItem from './pages/RentItem';
import CreateItem from './pages/CreateItem';
import MyRentals from './pages/MyRentals';
import MyListings from './pages/MyListings';
import Profile from './pages/Profile';
import PublicProfile from './pages/PublicProfile';
import Messages from './pages/Messages';
import MessageDetail from './pages/MessageDetail';
import ItemRequests from './pages/ItemRequests';
import ItemRequestDetail from './pages/ItemRequestDetail';
import CreateItemRequest from './pages/CreateItemRequest';
import MyRequests from './pages/MyRequests';
import EarningsDashboard from './pages/EarningsDashboard';
import PrivateRoute from './components/PrivateRoute';
import axios from 'axios';
import './App.css';

const API_URL = process.env.REACT_APP_API_URL || 'http://localhost:5001';

const AppContent: React.FC = () => {
  const { showAuthModal, authModalMode, closeAuthModal } = useAuth();
  const [hasAlphaAccess, setHasAlphaAccess] = useState<boolean | null>(null);
  const [checkingAccess, setCheckingAccess] = useState(true);

  useEffect(() => {
    const checkAlphaAccess = async () => {
      try {
        const response = await axios.get(`${API_URL}/alpha/verify-session`, {
          withCredentials: true,
        });
        setHasAlphaAccess(response.data.hasAccess);
      } catch (error) {
        console.error('Error checking alpha access:', error);
        setHasAlphaAccess(false);
      } finally {
        setCheckingAccess(false);
      }
    };

    checkAlphaAccess();
  }, []);

  // Show loading state while checking
  if (checkingAccess) {
    return (
      <div className="d-flex align-items-center justify-content-center min-vh-100">
        <div className="spinner-border text-primary" role="status">
          <span className="visually-hidden">Loading...</span>
        </div>
      </div>
    );
  }

  // Show alpha gate if no access
  if (!hasAlphaAccess) {
    return <AlphaGate />;
  }

  return (
    <>
      <Router>
        <div className="d-flex flex-column min-vh-100">
          <Navbar />
          <main className="flex-grow-1">
            <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/auth/google/callback" element={<GoogleCallback />} />
          <Route path="/verify-email" element={<VerifyEmail />} />
          <Route path="/reset-password" element={<ResetPassword />} />
          <Route path="/items" element={<ItemList />} />
          <Route path="/items/:id" element={<ItemDetail />} />
          <Route path="/users/:id" element={<PublicProfile />} />
          <Route
            path="/items/:id/edit"
            element={
              <PrivateRoute>
                <EditItem />
              </PrivateRoute>
            }
          />
          <Route
            path="/items/:id/rent"
            element={
              <PrivateRoute>
                <RentItem />
              </PrivateRoute>
            }
          />
          <Route
            path="/create-item"
            element={
              <PrivateRoute>
                <CreateItem />
              </PrivateRoute>
            }
          />
          <Route
            path="/my-rentals"
            element={
              <PrivateRoute>
                <MyRentals />
              </PrivateRoute>
            }
          />
          <Route
            path="/my-listings"
            element={
              <PrivateRoute>
                <MyListings />
              </PrivateRoute>
            }
          />
          <Route
            path="/profile"
            element={
              <PrivateRoute>
                <Profile />
              </PrivateRoute>
            }
          />
          <Route
            path="/messages"
            element={
              <PrivateRoute>
                <Messages />
              </PrivateRoute>
            }
          />
          <Route
            path="/messages/:id"
            element={
              <PrivateRoute>
                <MessageDetail />
              </PrivateRoute>
            }
          />
          <Route path="/item-requests" element={<ItemRequests />} />
          <Route path="/item-requests/:id" element={<ItemRequestDetail />} />
          <Route
            path="/create-item-request"
            element={
              <PrivateRoute>
                <CreateItemRequest />
              </PrivateRoute>
            }
          />
          <Route
            path="/my-requests"
            element={
              <PrivateRoute>
                <MyRequests />
              </PrivateRoute>
            }
          />
          <Route
            path="/earnings"
            element={
              <PrivateRoute>
                <EarningsDashboard />
              </PrivateRoute>
            }
          />
            </Routes>
          </main>
          <Footer />
        </div>
      </Router>

      <AuthModal
        show={showAuthModal}
        onHide={closeAuthModal}
        initialMode={authModalMode}
      />
    </>
  );
};

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

export default App;