import i18next from "i18next";
import React, { lazy, Suspense, useEffect } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { Route, Switch } from "react-router-dom";
import { createStructuredSelector } from "reselect";
import ErrorBoundary from "../components/error-boundary/error-boundary.component";
//Component Imports
import LoadingSpinner from "../components/loading-spinner/loading-spinner.component";
import { checkUserSession } from "../redux/user/user.actions";
import { selectCurrentUser } from "../redux/user/user.selectors";
// import { QUERY_BODYSHOP } from "../graphql/bodyshop.queries";
import PrivateRoute from "../utils/private-route";
import "./App.css";

const LandingPage = lazy(() => import("../pages/landing/landing.page"));
const ManagePage = lazy(() => import("../pages/manage/manage.page.container"));
const SignInPage = lazy(() => import("../pages/sign-in/sign-in.page"));
const Unauthorized = lazy(() =>
  import("../pages/unauthorized/unauthorized.component")
);

const mapStateToProps = createStructuredSelector({
  currentUser: selectCurrentUser
});
const mapDispatchToProps = dispatch => ({
  checkUserSession: () => dispatch(checkUserSession())
});
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(({ checkUserSession, currentUser }) => {
  useEffect(() => {
    checkUserSession();
    return () => {};
  }, [checkUserSession]);
  const { t } = useTranslation();
  if (currentUser && currentUser.language)
    i18next.changeLanguage(currentUser.language, (err, t) => {
      if (err)
        return console.log("Error encountered when changing languages.", err);
    });

  if (currentUser.authorized === null) {
    return <LoadingSpinner message={t("general.labels.loggingin")} />;
  }

  return (
    <div>
      <Switch>
        <ErrorBoundary>
          <Suspense fallback={<LoadingSpinner />}>
            <Route exact path='/' component={LandingPage} />
            <Route exact path='/unauthorized' component={Unauthorized} />

            <Route exact path='/signin' component={SignInPage} />

            <PrivateRoute
              //isAuthorized={HookCurrentUser.data.currentUser ? true : false}
              isAuthorized={currentUser.authorized}
              path='/manage'
              component={ManagePage}
            />
          </Suspense>
        </ErrorBoundary>
      </Switch>
    </div>
  );
});
