import React, { FunctionComponent, useState, useEffect } from 'react';
import { BrowserRouter, Route, Redirect, Switch } from "react-router-dom";
import { HomePage } from './HomePage/HomePage';
import { ProfilePage } from './ProfilePage/ProfilePage';
import { DashboardPage } from './DashboardPage/DashboardPage';
import { PrivateRoute } from './PrivateRoute';
import { useLoggedIn, LoggedInContext, getSavedLoggedIn, saveLoggedIn } from '../hooks/useLoggedIn';
import { useUserProfile } from '../gql/queries/user';
import { ProjectPage } from './ProjectPage/ProjectPage';
import { createClient } from '../util/apollo';
import { ApolloProvider } from '@apollo/client';

export interface AppProps {

}

export const App: FunctionComponent<AppProps> = () => {
  const [ loggedIn, setLoggedIn ] = useState(getSavedLoggedIn());

  const client = createClient((loggedIn) => {
    setLoggedIn(loggedIn);
  });

  useEffect(() => {
    saveLoggedIn(loggedIn);
  }, [loggedIn]);

  return (
    <ApolloProvider client={client}>
      <LoggedInContext.Provider value={loggedIn}>
        <UserSessionCheck setLoggedIn={setLoggedIn} />
        <BrowserRouter>
          <Switch>
            <Route path="/" exact component={HomePage} />
            <PrivateRoute path="/profile" exact component={ProfilePage} />
            <PrivateRoute path="/dashboard" exact component={DashboardPage} />
            <PrivateRoute path="/projects/:id" exact component={ProjectPage} />
            <Route component={() => <Redirect to="/" />} />
          </Switch>
        </BrowserRouter>
      </LoggedInContext.Provider>
    </ApolloProvider>
  );
}


interface UserSessionCheckProps {
  setLoggedIn: (boolean) => void
}

const UserSessionCheck: FunctionComponent<UserSessionCheckProps> = ({ setLoggedIn }) => {
  const { user, loading } = useUserProfile();

  useEffect(() => {
    if (loading) return;
    setLoggedIn(user.id !== '');
  }, [user]);

  return null;
};