import { useState, useEffect } from "react" import { Link, useNavigate } from "react-router" import { FormInput } from "@/components/shared/form-input" import { FormButton } from "@/components/shared/form-button" import { useAuth } from "@/app/context/auth-context" import { setTokens } from "@/lib/auth" export default function LoginPage() { const navigate = useNavigate() const { user, loading: authLoading, refreshUser } = useAuth() useEffect(() => { if (!authLoading && user) { navigate("/forms") } }, [user, authLoading, navigate]) const [form, setForm] = useState({ email: "", password: "" }) const [rememberMe, setRememberMe] = useState(false) const [errors, setErrors] = useState>({}) const [loading, setLoading] = useState(false) function handleChange(e: React.ChangeEvent) { setForm((prev) => ({ ...prev, [e.target.name]: e.target.value })) setErrors((prev) => ({ ...prev, [e.target.name]: "" })) } function validate() { const newErrors: Partial = {} if (!form.email.trim()) newErrors.email = "Email is required" if (!form.password) newErrors.password = "Password is required" return newErrors } async function handleSubmit(e: React.FormEvent) { e.preventDefault() const newErrors = validate() if (Object.keys(newErrors).length > 0) { setErrors(newErrors) return } setLoading(true) try { const res = await fetch("http://localhost:8080/api/auth/login", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ email: form.email, password: form.password, }), }) if (!res.ok) { const data = await res.json() setErrors({ general: data.message ?? "Invalid email or password" }) return } const data = await res.json() setTokens(data.access_token, data.refresh_token, rememberMe) refreshUser() navigate("/forms") } catch (err) { console.error(err) setErrors({ general: "Something went wrong. Please try again." }) } finally { setLoading(false) } } return (

Welcome back

Sign in to your FormCraft account

{errors.general && (

{errors.general}

)}
Forgot password?
{loading ? "Signing in..." : "Sign in"}

{"Don't have an account? "} Sign up

) }