import React, { useState, useEffect } from 'react';
import { createBrowserRouter, RouterProvider } from 'react-router';
import { AuthProvider, useAuth } from './contexts/AuthContext';
import { SocketProvider } from './contexts/SocketContext';
import RootLayout from './components/RootLayout';
import ProtectedLayout from './components/ProtectedLayout';
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 Renting from './pages/Renting';
import Owning from './pages/Owning';
import Profile from './pages/Profile';
import PublicProfile from './pages/PublicProfile';
import Messages from './pages/Messages';
import ForumPosts from './pages/ForumPosts';
import ForumPostDetail from './pages/ForumPostDetail';
import CreateForumPost from './pages/CreateForumPost';
import MyPosts from './pages/MyPosts';
import EarningsDashboard from './pages/EarningsDashboard';
import CompletePayment from './pages/CompletePayment';
import FAQ from './pages/FAQ';
import NotFound from './pages/NotFound';
import axios from 'axios';
import './App.css';

const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:5001';

const router = createBrowserRouter([
  {
    element: <RootLayout />,
    children: [
      // Public routes
      { path: '/', element: <Home /> },
      { path: '/auth/google/callback', element: <GoogleCallback /> },
      { path: '/verify-email', element: <VerifyEmail /> },
      { path: '/reset-password', element: <ResetPassword /> },
      { path: '/items', element: <ItemList /> },
      { path: '/items/:id', element: <ItemDetail /> },
      { path: '/users/:id', element: <PublicProfile /> },
      { path: '/forum', element: <ForumPosts /> },
      { path: '/forum/:id', element: <ForumPostDetail /> },
      { path: '/faq', element: <FAQ /> },

      // Protected routes group
      {
        element: <ProtectedLayout />,
        children: [
          { path: '/items/:id/edit', element: <EditItem /> },
          { path: '/items/:id/rent', element: <RentItem /> },
          { path: '/create-item', element: <CreateItem /> },
          { path: '/renting', element: <Renting /> },
          { path: '/complete-payment/:rentalId', element: <CompletePayment /> },
          { path: '/owning', element: <Owning /> },
          { path: '/profile', element: <Profile /> },
          { path: '/messages', element: <Messages /> },
          { path: '/forum/create', element: <CreateForumPost /> },
          { path: '/forum/:id/edit', element: <CreateForumPost /> },
          { path: '/my-posts', element: <MyPosts /> },
          { path: '/earnings', element: <EarningsDashboard /> },
        ],
      },

      // Catch-all route
      { path: '*', element: <NotFound /> },
    ],
  },
]);

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

  useEffect(() => {
    const checkAlphaAccess = async () => {
      // Bypass alpha access check if feature is disabled
      if (import.meta.env.VITE_ALPHA_TESTING_ENABLED !== 'true') {
        setHasAlphaAccess(true);
        setCheckingAccess(false);
        return;
      }

      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 <RouterProvider router={router} />;
};

const AppWithSocket: React.FC = () => {
  const { user } = useAuth();

  return (
    <SocketProvider isAuthenticated={!!user}>
      <AppContent />
    </SocketProvider>
  );
};

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

export default App;
