import axios from "axios";
import { useState } from "react";
import { useNavigate, Link } from "react-router-dom";
import TopBar from "../components/TopBar";

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);
                    }
                );
            })
            .catch((err) => {
                alert(err.response);
            });
    }

    return (
        <div className="forum-page">
            <TopBar user={undefined}/>
            <div className="forum-section">
                <h2>Register</h2>
                <form onSubmit={handleSubmit}>
                    <p>
                        {!/^[a-zA-Z0-9-_]+$/.test(username) && username.length != 0 && (
                            <span>Username can only contain letters, numbers, - and _</span>
                        )}
                    </p>
                    <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" disabled={!/^[a-zA-Z0-9-_]+$/.test(username)}>
                        Register
                    </button>
                </form>
                <Link to="/login">Login</Link>
            </div>
        </div>
    );
}