import React, { Component } from "react";
import { withRouter } from "react-router-dom";
import compose from "recompose/compose";
import { withStyles } from "@material-ui/core/styles";

import {
  Button,
  Divider,
  IconButton,
  AppBar,
  Toolbar,
  Typography,
  Link
} from "@material-ui/core";

import AccountCircle from "@material-ui/icons/AccountCircle";
import AddPhotoAlternateIcon from "@material-ui/icons/AddPhotoAlternate";
import MailOutlineIcon from "@material-ui/icons/MailOutline";
import VpnKeyIcon from "@material-ui/icons/VpnKey";
import MenuIcon from "@material-ui/icons/Menu";
import axios from "axios";

const styles = theme => ({
  root: {
    flexGrow: 1
  },

  menuButton: {
    marginRight: theme.spacing(2)
  },
  title: {
    flexGrow: 1
  }
});

class AppHeader extends Component {
  state = {
    user: null
  };
  // constructor(props) {
  //   super(props);
  //   this.state = {
  //     user: null
  //   };
  // }

  componentDidMount = () => {
    this.getCurrentUser();
  };

  componentWillReceiveProps = nextProp => {
    this.getCurrentUser();
  };

  getCurrentUser = async () => {
    const token = localStorage.getItem("token");
    if (token) {
      const user = await axios.get(
        "http://localhost:9000/api/auth/currentUser",
        { headers: { token: token } }
      );
      this.setState({ user: user.data });
    }
  };

  render() {
    const { classes } = this.props;
    const { user } = this.state;

    return (
      <div className={classes.root}>
        <AppBar position="static">
          <Toolbar>
            <IconButton
              edge="start"
              className={classes.menuButton}
              color="inherit"
              aria-label="menu"
              Link
              href="/"
            >
              <img src={require("../../image/icon.png")}></img>
            </IconButton>
            <Typography variant="h6" className={classes.title}></Typography>
            {!user ? (
              [
                <Button color="inherit" Link href="/LoginPage">
                  Login
                </Button>,
                <Button color="inherit" Link href="/RigisterPage">
                  rigister
                </Button>,
                <Button color="inherit" Link href="/RigisterShopPage">
                  rigistershop
                </Button>
              ]
            ) : (
              <div>
                {user.name}

                <Button
                  color="inherit"
                  onClick={() => {
                    localStorage.removeItem("token");
                    this.props.history.push("/");
                    this.setState({ user: null });
                  }}
                >
                  Logout
                </Button>
              </div>
            )}
          </Toolbar>
        </AppBar>
      </div>
    );
  }
}
export default compose(withStyles(styles), withRouter)(AppHeader);

// Redux
