"use client"; import { authClient } from "@/lib/auth-client"; import { Check, Eye, EyeOff, Loader2, Mail } from "lucide-react"; import Link from "next/link"; import { useSearchParams } from "next/navigation"; import { useState } from "react"; interface AuthFormProps { mode: "login" | "signup"; } export function AuthForm({ mode }: AuthFormProps) { const searchParams = useSearchParams(); const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [name, setName] = useState(""); const [error, setError] = useState(""); const [loading, setLoading] = useState(false); const [showPassword, setShowPassword] = useState(false); const [success, setSuccess] = useState(false); const isLogin = mode === "login"; const rawCallback = isLogin ? searchParams.get("callbackUrl") : null; const callbackUrl = rawCallback?.startsWith("/") && !rawCallback.startsWith("//") ? rawCallback : "/dashboard"; const title = isLogin ? "Sign in to your account" : "Create your account"; const submitLabel = isLogin ? "Sign In" : "Sign Up"; const switchText = isLogin ? "Don't have an account?" : "Already have an account?"; const switchHref = isLogin ? "/signup" : "/login"; const switchLabel = isLogin ? "Sign up" : "Sign in"; async function handleSubmit(e: React.FormEvent) { e.preventDefault(); setError(""); setLoading(true); try { if (isLogin) { const result = await authClient.signIn.email({ email, password, }); if (result.error) { setError(result.error.message || "Invalid email or password"); return; } // Full reload ensures middleware + server components re-evaluate with new auth state window.location.href = callbackUrl; } else { const result = await authClient.signUp.email({ email, password, name: name || email.split("@")[0], }); if (result.error) { setError(result.error.message || "Failed to create account"); return; } setSuccess(true); setTimeout(() => { window.location.href = "/dashboard"; }, 800); return; } } catch { setError("Something went wrong. Please try again."); } finally { setLoading(false); } } if (success) { return (
Redirecting to your dashboard...
{switchText}{" "} {switchLabel}