"use client";

import { useState } from "react";

const LoginForm = () => {
	const [handle, setHandle] = useState("");
	const [isLoading, setIsLoading] = useState(false);

	const handleSubmit = async (event: Event) => {
		event.preventDefault();

		setIsLoading(true);

		try {
			const response = await fetch("/oauth/login", {
				body: JSON.stringify({ handle }),
				headers: { "Content-Type": "application/json" },
				method: "POST"
			});
			const json = await response.json();

			if(!response.ok){
				throw new Error(json.error || "Login failed")
			}

			window.location.href = json.redirectURL;
		} catch (error) {
		} finally {
			setIsLoading(false);
		}
	};

	return (
		<form
			className="bg-amber-100 flex flex-col h-fit items-center justify-center p-4 rounded-2xl w-1/3"
			onSubmit={handleSubmit}
		>
			<div className="flex flex-col p-4 rounded-2xl w-full">
				<label
					className="text-emerald-900"
					htmlFor="handle"
				>
					Handle
				</label>
				<input
					className="bg-emerald-900 px-4 py-2 rounded-lg"
					id="handle"
					onChange={(event) => setHandle(event.currentTarget.value)}
					placeholder="alice.blacksky.app"
					type="text"
					value={handle}
				/>
			</div>
			<button
				className="hover:bg-emerald-800 bg-emerald-900  cursor-pointer px-4 py-2 rounded-lg"
				disabled={!handle || isLoading}
			>
				{isLoading ? "Logging in ..." : "Log into the Atmosphere"}
			</button>
		</form>
	);
};

export default LoginForm;
