import {Button, Col, Container, Form, Row} from 'react-bootstrap';
import {useState} from 'react';
import {login} from '../../api/authenticationAPI';
import {userData} from '../../recoilState/usersState';
import {useSetRecoilState} from 'recoil';
import {useHistory} from 'react-router-dom';

const Login = () => {
    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');
    const setUser = useSetRecoilState(userData);
    const history = useHistory();

    const loginHandler = async (evt) => {
        evt.preventDefault();
        const user = await login(username, password)

        // Can't set the user if the login failed.
        if (!user) {
            return;
        }

        setUser(user);

        // Navigate back to the previous page.
        history.goBack();
    }

    return <Container>
        <Row>
            <Col>
                <h3>Login</h3>
                <Form>
                    <Form.Group className="my-2">
                        <Form.Control type="username" placeholder="Username"
                                      value={username} onChange={evt => setUsername(evt.target.value)}/>
                    </Form.Group>

                    <Form.Group className="my-2">
                        <Form.Control type="password" placeholder="Password"
                                      value={password} onChange={evt => setPassword(evt.target.value)}/>
                    </Form.Group>

                    <Form.Group className="d-grid my-2" >
                        <Button variant="primary" type="submit" onClick={loginHandler}>
                            Login
                        </Button>
                    </Form.Group>
                </Form>
            </Col>
        </Row>
    </Container>
}

export default Login;
