import React, { useState, useEffect } from 'react';
import { Routes, Route, Navigate } from 'react-router-dom';
import Header from './components/Header';
import Footer from './components/Footer';
import Home from './pages/Home';
import Shop from './pages/Shop';
import About from './pages/About';
import Contact from './pages/Contact';
import Auth from './pages/Auth';
import VerifyEmail from './pages/VerifyEmail';
import VerifyEmailSuccess from './pages/VerifyEmailSuccess';
import ResetPassword from './pages/ResetPassword';
import authService from './services/authService';
import './App.css';
// import admin from './pages/Admin';
import Product from './pages/ProductDetails';
import ProductDetails from './pages/ProductDetails';
import Cart from './pages/Cart';
import Admin from './pages/Admin';

function App() {
  const [user, setUser] = useState(null);
  const [isAdmin, setIsAdmin] = useState(false);
  const [isLoading, setIsLoading] = useState(true);

  const fetchProfile = async (retryCount = 0) => {
    const maxRetries = 2;

    try {
      console.log('Fetching user profile...');
      const response = await authService.getProfile();
      console.log('Profile response:', response);
      setUser(response.user);
      setIsAdmin(response.user.role === 'admin');
      console.log('User authenticated:', response.user.email);
    } catch (error) {
      console.error('Failed to fetch profile:', error);
      console.error('Error status:', error.response?.status);
      console.error('Error message:', error.response?.data?.message || error.message);

      // Only logout on authentication errors (401/403), not network errors
      if (error.response && (error.response.status === 401 || error.response.status === 403)) {
        console.log('Authentication error - logging out');
        setUser(null);
        setIsAdmin(false);
      } else if (retryCount < maxRetries) {
        // For network errors, retry after a short delay
        console.log(`Network error - retrying (${retryCount + 1}/${maxRetries})`);
        setTimeout(() => fetchProfile(retryCount + 1), 1000);
        return; // Don't set loading to false yet
      } else {
        console.log('Max retries reached - keeping current auth state');
      }
    } finally {
      if (retryCount === 0) {
        setIsLoading(false);
      }
    }
  };

  useEffect(() => {
    // Add a small delay to ensure cookies are properly set after login
    const timer = setTimeout(() => {
      fetchProfile();
    }, 100);

    return () => clearTimeout(timer);
  }, []);

  const handleLogin = async () => {
    return fetchProfile();
  };

  const handleLogout = () => {
    authService.logout();
    setUser(null);
    setIsAdmin(false);
  };

  if (isLoading) {
    return (
      <div className="App">
        <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
          <div>Loading...</div>
        </div>
      </div>
    );
  }

  return (
    <div className="App">
      <Header user={user} onLogout={handleLogout} isAdmin={isLoading ? false : isAdmin} />
      <main>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/shop" element={<Shop />} />
          <Route path="/about" element={<About />} />
          <Route path="/contact" element={<Contact />} />
          <Route path="/auth" element={user ? <Navigate to="/" replace /> : <Auth onLogin={handleLogin} />} />
          <Route path="/verify-email" element={<VerifyEmail />} />
          <Route path="/verify-email-success" element={<VerifyEmailSuccess />} />
          <Route path="/reset-password" element={<ResetPassword />} />
          {/* <Route path="/admin" element={<admin />} /> */}
          <Route path="/productdetail" element={<ProductDetails/>}/>
          <Route path="/cart" element={<Cart/>} />
          <Route path="/admin" element={isAdmin ? <Admin/> : <Navigate to="/auth" replace />} />
        </Routes>
      </main>
      <Footer />
    </div>
  );
}

export default App;
