import PrimaryButton from "@/components/button/PrimaryButton";
import PasswordInput from "@/components/input/PasswordInput";
import TextInput from "@/components/input/TextInput";
import { useAuth } from "@/providers/AuthProvider";
import { useTimedModal } from "@/providers/TimedModalProvider";
import { Link, Navigate, useNavigate } from "react-router";


export default function LoginPage(){
	const { jwt, setTokenData } = useAuth();
	const navigate = useNavigate();
	const { addSuccessMessage, addErrorMessage } = useTimedModal();


	const login = async (formData: FormData) => {
		const username = formData.get("username") as string;
		const password = formData.get("password") as string;


		await fetch(`${import.meta.env.VITE_API_URL}/auth/token`, {
			method: "GET",
			headers: {
				Authorization: "Basic " + btoa(`${username}:${password}`)
			},
			credentials: "include"
		})
		.then(async (response) => {
			if(response.status === 200){
				addSuccessMessage("Logged in successfully");
				const json = await response.json();
				setTokenData(json);
				navigate("/raidGroup");
			}
			else{
				addErrorMessage("Failed to log in: " + ((await response.json()).errors as string[]).join(",\n"));
			}
		})
		.catch(error => {
			addErrorMessage("Failed to log in: " + error);
		});
	}


	if(jwt){
		return <Navigate to="/"/>;
	}


	return (
		<main>
			<form
				action={login}
				className="flex flex-col items-center justify-center space-y-8"
			>
				<div
					className="mx-auto"
				>
					<TextInput
						id="username"
						name="username"
						placeholder="Username"
					/>
				</div>
				<div
					className="mx-auto"
				>
					<PasswordInput
						id="password"
						name="password"
						placeholder="Password"
					/>
				</div>
				<div
					className="flex flex-row justify-center items-center"
				>
					<PrimaryButton
						type="submit"
					>
						Login
					</PrimaryButton>
				</div>
				<div
					className="flex flex-row justify-center items-center"
				>
					<Link
						to="/forgotPassword"
					>
						Forgot Password?
					</Link>
				</div>
			</form>
		</main>
	);
}
