import { useClient } from "@splitsoftware/splitio-react";
import { Button, Result } from "antd";
import LogRocket from "logrocket";
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 DocumentEditorContainer from "../components/document-editor/document-editor.container";
import ErrorBoundary from "../components/error-boundary/error-boundary.component";
//Component Imports
import LoadingSpinner from "../components/loading-spinner/loading-spinner.component";
import DisclaimerPage from "../pages/disclaimer/disclaimer.page";
import LandingPage from "../pages/landing/landing.page";
import TechPageContainer from "../pages/tech/tech.page.container";
import { setOnline } from "../redux/application/application.actions";
import { selectOnline } from "../redux/application/application.selectors";
import { checkUserSession } from "../redux/user/user.actions";
import {
  selectBodyshop,
  selectCurrentUser,
} from "../redux/user/user.selectors";
import PrivateRoute from "../utils/private-route";
import "./App.styles.scss";

const ResetPassword = lazy(() =>
  import("../pages/reset-password/reset-password.component")
);
const ManagePage = lazy(() => import("../pages/manage/manage.page.container"));
const SignInPage = lazy(() => import("../pages/sign-in/sign-in.page"));

const CsiPage = lazy(() => import("../pages/csi/csi.container.page"));
const MobilePaymentContainer = lazy(() =>
  import("../pages/mobile-payment/mobile-payment.container")
);

const mapStateToProps = createStructuredSelector({
  currentUser: selectCurrentUser,
  online: selectOnline,
  bodyshop: selectBodyshop,
});
const mapDispatchToProps = (dispatch) => ({
  checkUserSession: () => dispatch(checkUserSession()),
  setOnline: (isOnline) => dispatch(setOnline(isOnline)),
});

export function App({
  bodyshop,
  checkUserSession,
  currentUser,
  online,
  setOnline,
}) {
  const client = useClient();

  useEffect(() => {
    if (!navigator.onLine) {
      setOnline(false);
    }

    checkUserSession();
  }, [checkUserSession, setOnline]);

  //const b = Grid.useBreakpoint();
  // console.log("Breakpoints:", b);

  const { t } = useTranslation();

  window.addEventListener("offline", function (e) {
    setOnline(false);
  });

  window.addEventListener("online", function (e) {
    setOnline(true);
  });
  useEffect(() => {
    if (currentUser.authorized && bodyshop) {
      client.setAttribute("imexshopid", bodyshop.imexshopid);

      if (client.getTreatment("LogRocket_Tracking") === "on") {
        console.log("LR Start");
        LogRocket.init("gvfvfw/bodyshopapp");
      }
    }
  }, [bodyshop, client, currentUser.authorized]);

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

  if (!online)
    return (
      <Result
        status="warning"
        title={t("general.labels.nointernet")}
        subTitle={t("general.labels.nointernet_sub")}
        extra={
          <Button
            type="primary"
            onClick={() => {
              window.location.reload();
            }}
          >
            {t("general.actions.refresh")}
          </Button>
        }
      />
    );

  return (
    <Switch>
      <Suspense fallback={<LoadingSpinner message="ImEX Online" />}>
        <ErrorBoundary>
          <Route exact path="/" component={LandingPage} />
        </ErrorBoundary>
        <ErrorBoundary>
          <Route exact path="/signin" component={SignInPage} />
        </ErrorBoundary>
        <ErrorBoundary>
          <Route exact path="/resetpassword" component={ResetPassword} />
        </ErrorBoundary>
        <ErrorBoundary>
          <Route exact path="/csi/:surveyId" component={CsiPage} />
        </ErrorBoundary>
        <ErrorBoundary>
          <Route exact path="/disclaimer" component={DisclaimerPage} />
        </ErrorBoundary>
        <ErrorBoundary>
          <Route
            exact
            path="/mp/:paymentIs"
            component={MobilePaymentContainer}
          />
        </ErrorBoundary>
        <ErrorBoundary>
          <PrivateRoute
            isAuthorized={currentUser.authorized}
            path="/manage"
            component={ManagePage}
          />
        </ErrorBoundary>
        <ErrorBoundary>
          <PrivateRoute
            isAuthorized={currentUser.authorized}
            path="/tech"
            component={TechPageContainer}
          />
        </ErrorBoundary>
        <ErrorBoundary>
          <PrivateRoute
            isAuthorized={currentUser.authorized}
            path="/edit"
            component={DocumentEditorContainer}
          />
        </ErrorBoundary>
      </Suspense>
    </Switch>
  );
}

export default connect(mapStateToProps, mapDispatchToProps)(App);
