import React, { useState } from 'react';
import Router from 'next/router';

export const Login = () => {

    const [csrfToken, setscrf] = useState('')
    const [username, setUsername] = useState('')
    const [password, setPassword] = useState('')

    React.useEffect(() => {

        fetch("http://localhost:8000/users/csrf/", {
            credentials: "include",
        })
            .then((res) => {
                let csrfToken = res.headers.get("X-CSRFToken")
                setscrf(csrfToken);
            })
            .catch((err) => {
                console.log(err)
            })
    }, [])

    function handleSubmit(e) {
        e.preventDefault();
        fetch("http://localhost:8000/users/login/", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                "X-CSRFToken": csrfToken,
            },
            credentials: "include",
            body: JSON.stringify({ username: username, password: password }),
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Connecting problem');
                }
            })
            .then((data) => {
                console.log(data);
                Router.push('/');
            })
            .catch((err) => {
                console.log(err);
            });

    }

    return (
        <>
            <form onSubmit={handleSubmit} novalidate>
                <div className="container">
                    <label htmlFor="username"><b>Username</b></label>
                    <input type="text" placeholder="Enter Username" name="username" onChange={(e) => setUsername(e.target.value)}
                        required />

                    <label htmlFor="password"><b>Password</b></label>
                    <input type="password" placeholder="Enter Password" name="password" onChange={(e) => setPassword(e.target.value)}
                        required />

                    <button type="submit">Login</button>
                </div>
            </form>
        </>
    )
}

export default Login;