'use client'; import { z } from 'zod'; import { zodResolver } from '@hookform/resolvers/zod'; import { useForm } from 'react-hook-form'; import { Card, CardContent, CardDescription, CardHeader, CardTitle, Form, FormControl, FormField, FormItem, FormLabel, FormMessage, Input, } from '@/components/ui'; import Link from 'next/link'; import { forgotPassword } from '@/lib/queries'; import { useAuth } from '@/lib/hooks/context'; import { useEffect, useState, type ComponentProps } from 'react'; import { useRouter } from 'next/navigation'; import { useSupabaseClient } from '@/utils/supabase'; import { StatusMessage, SubmitButton } from '@/components/default/forms'; import { cn } from '@/lib/utils'; const forgotPasswordFormSchema = z.object({ email: z.string().email({ message: 'Please enter a valid email address.' }), }); type ForgotPasswordCardProps = { cardClassName?: ComponentProps['className']; cardProps?: Omit, 'className'>; cardTitleClassName?: ComponentProps['className']; cardTitleProps?: Omit, 'className'>; cardDescriptionClassName?: ComponentProps['className']; cardDescriptionProps?: Omit, 'className'>; signUpLinkClassName?: ComponentProps['className']; signUpLinkProps?: Omit, 'className' | 'href'>; formClassName?: ComponentProps<'form'>['className']; formProps?: Omit, 'className' | 'onSubmit'>; formLabelClassName?: ComponentProps['className']; formLabelProps?: Omit, 'className'>; buttonProps?: ComponentProps; }; export const ForgotPasswordCard = ({ cardClassName, cardProps, cardTitleClassName, cardTitleProps, cardDescriptionClassName, cardDescriptionProps, signUpLinkClassName, signUpLinkProps, formClassName, formProps, formLabelClassName, formLabelProps, buttonProps = { pendingText: 'Sending Reset Link...', }, }: ForgotPasswordCardProps) => { const router = useRouter(); const { isAuthenticated, loading, refreshUser } = useAuth(); const [statusMessage, setStatusMessage] = useState(''); const supabase = useSupabaseClient(); const form = useForm>({ resolver: zodResolver(forgotPasswordFormSchema), defaultValues: { email: '', }, }); useEffect(() => { if (isAuthenticated) router.push('/') }, [isAuthenticated, router]); const handleForgotPassword = async (values: z.infer) => { try { setStatusMessage(''); const formData = new FormData(); formData.append('email', values.email); if (!supabase) throw new Error('Supabase client not found'); const result = await forgotPassword(supabase, formData); if (result.error) throw new Error(result.error.message); await refreshUser(); setStatusMessage('Check your email for a link to reset your password.'); form.reset(); router.push(''); } catch (error) { setStatusMessage( `Error: ${error instanceof Error ? error.message : 'Could not sign in!'}`, ); } }; return ( Forgot Password Don't have an account?{' '} Sign up!
( Email )} /> Reset Password {statusMessage && (statusMessage.includes('Error') || statusMessage.includes('error') || statusMessage.includes('failed') || statusMessage.includes('invalid') ? ( ) : ( ))}
); };