import React, { useEffect } from "react";
import { BrowserRouter, Route, Switch, Redirect } from "react-router-dom";

// components
import Layout from "./Layout/Layout";

// pages
import Error from "../pages/error";
import Login from "../pages/login";
import ServerNotAvailable from "../features/server/availability/components/ServerNotAvailable";
import { useTuitioToken } from "@flare/tuitio-client-react";

export default function App() {
  const { valid: authenticated } = useTuitioToken();

  return (
    <BrowserRouter basename={process.env.PUBLIC_URL || ""}>
      <Switch>
        <Route exact path="/" render={() => <Redirect to="/dashboard" />} />
        <PrivateRoute
          path="/server-not-available"
          component={ServerNotAvailable}
        />
        <PublicRoute path="/login" component={Login} />
        <PrivateRoute path="/" component={Layout} />
        <Route component={Error} />
      </Switch>
    </BrowserRouter>
  );

  function PrivateRoute({ component, ...rest }) {
    return (
      <Route
        {...rest}
        render={(props) =>
          authenticated ? (
            React.createElement(component, props)
          ) : (
            <Redirect
              to={{
                pathname: "/login",
                state: {
                  from: props.location
                }
              }}
            />
          )
        }
      />
    );
  }

  function PublicRoute({ component, ...rest }) {
    return (
      <Route
        {...rest}
        render={(props) =>
          authenticated ? (
            <Redirect
              to={{
                pathname: "/"
              }}
            />
          ) : (
            React.createElement(component, props)
          )
        }
      />
    );
  }
}
