import React, { Component } from "react";
import { MuiPickersUtilsProvider } from "@material-ui/pickers";
import DateFnsUtils from "@date-io/date-fns";
import { th } from "date-fns/locale";
import { MuiThemeProvider, createMuiTheme } from "@material-ui/core/styles";
import axios from "axios";
import { connect } from "react-redux";
import { setUser } from "./actions/user";
import Routes from "./routes/index";

const theme = createMuiTheme({
  fontFamily: `'Prompt', sans-serif`,
  typography: {
    useNextVariants: true,
    fontFamily: `'Prompt', sans-serif`
  },
  palette: {
    // primary: {
    //     light: '#80DEEA',
    //     main: '#1a8a98',
    //     dark: '#00838F',
    //     contrastText: '#fff'
    // },
    // secondary: {
    //     light: '#ff7961',
    //     main: '#f44336',
    //     dark: '#ba000d',
    //     contrastText: '#000'
    // }
  }
});

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      isReady: false
    };
  }

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

  render() {
    const { isReady } = this.state;

    return isReady ? (
      <MuiPickersUtilsProvider utils={DateFnsUtils} locale={th}>
        <MuiThemeProvider theme={theme}>
          <Routes />
        </MuiThemeProvider>
      </MuiPickersUtilsProvider>
    ) : (
      <div />
    );
  }
}

const mapStateToProps = state => ({});

const mapDispatchToProps = dispatch => {
  return {
    setUser: userData => dispatch(setUser(userData))
  };
};

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