"use client"; import { useState, useEffect } from "react"; import { useRouter, useSearchParams } from "next/navigation"; import { useTranslations } from "next-intl"; import { z } from "zod"; import { useForm } from "react-hook-form"; import { zodResolver } from "@hookform/resolvers/zod"; import { Button } from "@/components/button"; import { LocaleLink } from "@/components/locale-link"; import { FormShell } from "@/features/forms/components/form-shell"; import { AuthMessageCard } from "@/features/forms/components/auth-message-card"; import { FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form"; import { Input } from "@/features/forms/components/input"; import { toast } from "sonner"; const resetPasswordSchema = z.object({ password: z.string().min(8, "Password must be at least 8 characters"), confirmPassword: z.string(), }).refine((data) => data.password === data.confirmPassword, { message: "Passwords don't match", path: ["confirmPassword"], }); type ResetPasswordInput = z.infer; export default function ResetPasswordPage() { const router = useRouter(); const searchParams = useSearchParams(); const t = useTranslations(); const [isLoading, setIsLoading] = useState(false); const [isValidToken, setIsValidToken] = useState(null); const token = searchParams.get("token"); const form = useForm({ resolver: zodResolver(resetPasswordSchema), defaultValues: { password: "", confirmPassword: "", }, }); useEffect(() => { if (!token) { setIsValidToken(false); return; } // Verify token validity fetch(`/api/auth/verify-reset-token?token=${token}`) .then(res => res.json()) .then(data => { setIsValidToken(data.valid); }) .catch(() => { setIsValidToken(false); }); }, [token]); const onSubmit = async (data: ResetPasswordInput) => { if (!token) { toast.error("Invalid reset link"); return; } setIsLoading(true); try { const response = await fetch("/api/auth/reset-password", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ token, password: data.password, }), }); if (response.ok) { toast.success("Password reset successfully!"); setTimeout(() => { router.push("/login"); }, 2000); } else { const error = await response.json(); toast.error(error.message || "Failed to reset password"); } } catch (error) { toast.error("An error occurred. Please try again."); } finally { setIsLoading(false); } }; if (isValidToken === null) { return (
); } if (isValidToken === false) { return (

Please request a new password reset link.

); } return ( form={form} title="Reset your password" description="Enter your new password below." onSubmit={onSubmit} submitText="Reset Password" submitLoadingText="Resetting..." isLoading={isLoading} footer={
Back to Login
} > ( New Password )} /> ( Confirm Password )} /> ); }