import './css/Login.css'
import Sidebar from './Components/Sidebar'
import Cookies from 'js-cookie'
import banner from "/src/assets/banner.png"
import { default as axios } from 'axios'
import { config } from './main'
import { useNavigate } from 'react-router'
import React, { useEffect } from 'react'

function Login() {
	let navigate = useNavigate();
	if (Cookies.get("token") && Cookies.get("token").startsWith("HajeebToken ")) {
		useEffect(() => {
			return navigate("/");
		}, [])
	}

	const handleSubmit = async (e) => {
		e.preventDefault();
		document.getElementById("submit").disabled = true;

		const formData = new FormData(e.target);
		let response = await axios.post(config.serverURL + "/account/token", {
			username: formData.get("username"),
			password: formData.get("password")
		})

		if(response.data.error) { // Login unsuccessful
			document.getElementById("submit").disabled = false;
			return alert(`Login error: ${response.data.message}`);
		}

		// Login successful
		Cookies.set("token", `HajeebToken ${response.data.token}`);
		return navigate("/");
	};

	return (
		<>
			<div className="main">
				<Sidebar />
				<div className="login-container">
					<form className="login" id="form" onSubmit={handleSubmit}>
						<img src={banner} width="300px"></img>
						<input type="text" placeholder="username" name="username"></input>
						<input type="password" placeholder="password" name="password"></input>
						<input type="submit" value="Log in/Sign up/Register/Enter Website" id="submit"></input>
					</form>
				</div>
			</div>
		</>
	)
}

export default Login
