import React, { useRef } from 'react';
import { Link as RouterLink } from 'react-router-dom';
import { Button, Container, CssBaseline, Grid, Link, TextField, Typography } from '@material-ui/core';
import { useUserContext } from '../Contexts/UserContext';
import useStyles from '../Styles';

export default function SignInForm() {
    const classes = useStyles();
    const emailEl = useRef(null);
    const passwordEl = useRef(null);
    const { fetching, signIn, setError } = useUserContext();
    const onSubmit = async (event) => {
      try {
        event.preventDefault();
        const username = emailEl.current.value;
        const password = passwordEl.current.value;
        await signIn(username, password);
      }
      catch (e) {
        setError(e.message);
      }
    };

    return (
      <Container component="main" maxWidth="xs">
        <CssBaseline />
        <div className={classes.paper}>
          <Typography component="h1" variant="h5">
            Sign in
          </Typography>
          <form className={classes.form} noValidate action="{onSubmit}">
            <TextField
              variant="outlined"
              margin="normal"
              required
              fullWidth
              id="email"
              label="Email Address"
              name="email"
              autoComplete="email"
              autoFocus
              inputRef={emailEl}
            />
            <TextField
              variant="outlined"
              margin="normal"
              required
              fullWidth
              name="password"
              label="Password"
              type="password"
              id="password"
              autoComplete="current-password"
              inputRef={passwordEl}
            />
            <Button
              type="submit"
              disabled={fetching}
              fullWidth
              variant="contained"
              color="primary"
              className={classes.submit}
              onClick={onSubmit}
            >
              { fetching ? "Signing In..." : "Sign In" }
            </Button>
            <Grid container>
              <Grid item>
                <Link component={RouterLink} to="/signup" variant="body2">
                  {"Don't have an account? Sign Up"}
                </Link>
              </Grid>
            </Grid>
          </form>
        </div>
      </Container>
    );
  }