import React, { useEffect } from "react";
import { Redirect, Route } from "react-router-dom";
import { connect } from "react-redux";
import { Typography } from "@mui/material";
import { loadUser } from "../store/auth/actions";
import store from "../store";
import LoginPage from "../pages/loginPage";

// Private route checks if user is logged in
function PrivateRoute({ component: Component, auth, ...rest }) {
  return (
    <Route
      {...rest}
      render={(props) => {
        // if authentication is loading, show loading text
        if (auth.isLoading) {
          return <Typography variant="h2">Loading...</Typography>;
        }
        // if user is not logged in, redirect to login page
        else if (!auth.isAuthenticated) {
          return <LoginPage />;
          // return <Redirect to="/login" />;
        }
        // if user is logged in, show requested component
        else {
          return <Component {...props} />;
        }
      }}
    />
  );
}

const mapStateToProps = (state) => ({
  auth: state.auth,
});

export default connect(mapStateToProps)(PrivateRoute);
