import React, { useState } from 'react';
import { TextField, Button, Paper, Container, } from '@material-ui/core';
import {Grid, GridCell, GridRow} from '@rmwc/grid';
import useStyles from '../../components/Styles';
import { useHistory } from "react-router-dom";
import { connect } from "react-redux";
import { login } from "../../actions.js"; 

const Login = ({handleLogin}) => {
  const classes = useStyles();
  const history = useHistory();
  const [loginData, setLoginData] = useState({
    username: '', password: ''
  })

  const handleSubmit = (e) => {
    e.preventDefault();
    handleLogin(loginData.username,loginData.password).then(() => {
      history.push("/todoList");
    });
  }

  return (
    <Container component="main" maxWidth="xs">
      <Paper elevation={3} className={classes.paper}>
        <form autoComplete="off" onSubmit={handleSubmit} className={classes.form}>
          <Grid container spacing={2}>
          <GridRow>
            <GridCell span={12}>
              <TextField 
                fullwidth 
                name="name" 
                label="Username" 
                className="loginField"
                value={loginData.username}
                onChange={(e) => setLoginData({...loginData, username: e.target.value})}    
              />
            </GridCell>
            
            <GridCell span={12}>
              <TextField 
                fullwidth
                name="password" 
                label="Password"
                type="password"
                className="loginField"
                value={loginData.password}
                onChange={(e) => setLoginData({...loginData, password: e.target.value})} 
                />
              </GridCell>
              <GridCell span={12}>
                <Button type="submit" variant="contained" className={classes.buttonSubmit} color="primary" size="large">Login</Button>
              </GridCell>
            </GridRow>

          </Grid>
          
        </form>
      </Paper>
    </Container>
  );
};

export default connect(
	(state, ownProps) => {
		const { auth } = state;
		return Object.assign({}, { auth: auth }, ownProps);
	},
	(dispatch) => {
		return { handleLogin: (username,password) => dispatch(login(username,password)) };
	}
)(Login);