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

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

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

    return (
        <div className="forum-page">
            <TopBar user={undefined}/>
            <div className="forum-section">
                <h2>Login</h2>
                <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">Login</button>
                </form>
                <Link to="/register">Register</Link>
            </div>
        </div>
    );
}