import { useEffect } from 'react';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import Home from './pages/Home';
import Cart from './pages/Cart';
import Login from './pages/Login';
import Products from './pages/Products';
import Product from './pages/Products/Product';
import Checkout from './pages/Checkout';
import Navbar from './components/Navbar';
import Footer from './components/Footer/Footer';
import Header from './components/Header';
import Loader from './components/Loader';
import theme from './theme/theme';
import { ThemeProvider, Box } from '@mui/material';
import { fetchCart, createCart } from './redux/slices/cartSlice';
import { useSelector, useDispatch } from 'react-redux';
import Collection from './pages/Collection';
import customerService from './services/CustomerService';
import Maintainance from './pages/Maintainance';

const isEmptyObject = (obj) => Object.keys(obj).length === 0 && obj.constructor === Object;

function App() {

  const dispatch = useDispatch()

  useEffect(() => {

    //Check if cart exist
    let cartHistory = localStorage.getItem('amber-cart');
    cartHistory = cartHistory ? JSON.parse(cartHistory) : {};

    // if we got cart, then just fetch from BE based on ID
    if (!isEmptyObject(cartHistory)) {

      dispatch(fetchCart(cartHistory.id));

    }else{

      dispatch(createCart())

    }


  }, [])

  return (
    <ThemeProvider theme={theme}>
      
      <Loader />
      <Header />
      <Navbar />
      <BrowserRouter>
        <Routes>
          <Route path='/' element={<Home />} />
          <Route path='/login' element={<Login />} />

          <Route path='products'>
            {/* All Products */}
            <Route index element={<Products />} />

            {/* Single Product */}
            <Route path=':pid' element={<Product />} />

          </Route>
          <Route path='/cart' element={<Cart />} />
          <Route path='/checkout' element={<Checkout />} />

          <Route path='/collection/:pid' element={<Collection />}/>

        </Routes>
      </BrowserRouter>
      <Footer />
    </ThemeProvider>
  );
}



export default App;
