import { useState,useEffect } from 'react';
import { UserProvider } from './UserContext';
import 'bootstrap/dist/css/bootstrap.min.css';
// Import React Router DOM
import { BrowserRouter as Router } from 'react-router-dom';
import { Route, Routes } from 'react-router-dom';
import { Container } from 'react-bootstrap';

import NavbarApp from './components/NavbarApp';
import Register from './pages/Register';
import Login from './pages/Login';
import Error from './pages/Error';
import Logout from './pages/Logout';
import AddProduct from './pages/AddProduct';
import Profile from './pages/Profile';
import Home from './pages/Home';
import Products from './pages/Products';
import PreviewProducts from './components/PreviewProducts';
import ProductView from './pages/ProductView';
import ProductDetails from './components/ProductDetails';
import OrderHistory from './pages/OrderHistory';
import './App.css';


function App() {
    // State hook for user state that's defined here for a global scope
  // This will be used to store the user information and will be used for validating if a user is logged in on the app or not

  const [currentForm, setCurrentForm]= useState('login');

  const toggleForm=(formName) =>{
    setCurrentForm(formName);
  }
  const [user, setUser] = useState({
    id:null,
    isAdmin:null
  });

  // Function for clearing localStorage on logout
  const unsetUser = () => {
    localStorage.clear();
  }

  // used to check if the user information is properly stored upon login and the localStorage information is cleared upon logout.
  useEffect(() => {
    console.log(user);
    console.log(localStorage);

    fetch(`${process.env.REACT_APP_API_URL}/users/userdetail`, {
      headers: {
        Authorization: `Bearer ${localStorage.getItem("token")}`
      }
    })
    .then(res => res.json())
    .then(data => {
      console.log(data);

      // Changes the global "user" state to store the "id" and the "isAdmin" properties of the user which will be used for validation across the whole application
      if(typeof data._id !== "undefined"){

        setUser({
          id: data._id,
          isAdmin: data.isAdmin
        })
      } else {

        setUser({
          id: null,
          isAdmin: null
        })
      }

    })

  }, []);


  return (
  
    <UserProvider value={{ user, setUser, unsetUser }}>
    <Router>
      <Container fluid>
        <NavbarApp />
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/products" element={<Products />} /> 
          <Route path="/orders" element={<OrderHistory />} />
          <Route path="/profile" element={<Profile/>} />
          <Route path="/products/:productId" element={<ProductView />} /> *
          <Route path="/register" element={<Register />} />
          <Route path="/orderHistory" element={<OrderHistory/>} />
          <Route path="/ProductDetails" element={<ProductDetails />} />
          <Route path="/register" element={<Register onFormSwitch={toggleForm}/>} />
          <Route path="/addproduct" element={<AddProduct />} />
          <Route path="/login" element={<Login onFormSwitch={toggleForm}/>} />
           <Route path="/logout" element={<Logout/>} /> 
          

            // the * will catch all the error if there are any links that has been put but doesnt exist.
           <Route path="*" element={<Error />} /> 
        </Routes>
      </Container>
    </Router>
  </UserProvider>
  
  )
}

export default App;
