import axios from "axios";
import { useState } from "react";
import { useNavigate, Link } from "react-router-dom";

export default function Register () {
    const [username, setUsername] = useState("");
    const [password, setPassword] = useState("");
    const navigate = useNavigate();

    function handleSubmit(e: React.FormEvent) {
        e.preventDefault();
        axios.post("/api/auth/register", { username, password }).then(() => {
            axios
                .post("/api/auth/login", { username, password })
                .then((res) => {
                    localStorage.setItem("token", res.data.token);
                    navigate("/");
                })
                .catch((err) => {
                    alert(err.response.data.message);
                }
            );
        });
    }

    return (
        <div>
            <Link to="/">Home</Link>
            <h1>Register</h1>
            <form onSubmit={handleSubmit}>
                <input
                    type="text"
                    placeholder="Username"
                    value={username}
                    onChange={(e) => setUsername(e.target.value)}
                />
                <input
                    type="password"
                    placeholder="Password"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                />
                <button type="submit">Register</button>
            </form>
            <Link to="/login">Login</Link>
        </div>
    );
}