import React, { useState, useEffect } from 'react';
import { BrowserRouter as Router, Switch, Route, Redirect } from "react-router-dom";
import { Button, Dimmer, Loader } from "semantic-ui-react";
import { connect } from "react-redux";
import { getUser, isAuthenticated } from "../reducers";
import { signout, postAccount } from '../actions';
import Home from '../pages/Home';
import Login from '../pages/Login';
import PrivateRoute from './PrivateRoute';
import Register from '../pages/Register';

function App({authenticated, user, signout, postAccount}) {

  const [redirectTo, setRedirectTo] = useState<string | undefined>(undefined);

  useEffect(() => {
    if (!user && authenticated) {
      postAccount()
    }
  }, [postAccount, user, authenticated])


  const handleLogout = () => {

    signout(() => {
       setRedirectTo("/login");
    })
  }

  if (redirectTo) {
    return <Redirect to={redirectTo} />
  }

  if (!user && authenticated) {
    return (
      <Dimmer active inverted>
        <Loader inverted>Loading</Loader>
      </Dimmer>
    );
  }

  const LogoutButton = () => {
    if (authenticated) {
      return (
        <Button basic color="grey"
        floated="right"
        onClick={handleLogout}
        style={{ position: "absolute", right: "0", top: "0", margin: "16px 16px 0 0" }} >
        Logout
      </Button>
      )
    }

    return null;

  }

  return (
    <>
       <LogoutButton></LogoutButton>

      <Router>
        <Switch>
          <Route path="/login" component={Login} />
          <Route path="/signup" component={Register} />
          <PrivateRoute path="/" component={Home} />
        </Switch>
      </Router>
    </>
  );
}


const mapStateToProps = (state) => {
  return {
    user: getUser(state),
    authenticated: isAuthenticated(state)
  };
}

const mapDispatchToProps = {
  isAuthenticated,
  getUser,
  signout,
  postAccount
};

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