'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/actions';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/components/context/auth';
import { useEffect, useState } from 'react';
import { StatusMessage, SubmitButton } from '@/components/default';

const formSchema = z.object({
  email: z.string().email({
    message: 'Please enter a valid email address.',
  }),
});

const ForgotPassword = () => {
  const router = useRouter();
  const { isAuthenticated, isLoading, refreshUserData } = useAuth();
  const [statusMessage, setStatusMessage] = useState('');

  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      email: '',
    },
  });

  // Redirect if already authenticated
  useEffect(() => {
    if (isAuthenticated) {
      router.push('/');
    }
  }, [isAuthenticated, router]);

  const handleForgotPassword = async (values: z.infer<typeof formSchema>) => {
    try {
      setStatusMessage('');
      const formData = new FormData();
      formData.append('email', values.email);
      const result = await forgotPassword(formData);
      if (result?.success) {
        await refreshUserData();
        setStatusMessage(
          result?.data ?? 'Check your email for a link to reset your password.',
        );
        form.reset();
        router.push('');
      } else {
        setStatusMessage(`Error: ${result.error}`);
      }
    } catch (error) {
      setStatusMessage(
        `Error: ${error instanceof Error ? error.message : 'Could not sign in!'}`,
      );
    }
  };

  return (
    <Card className='min-w-xs md:min-w-sm'>
      <CardHeader>
        <CardTitle className='text-2xl font-medium'>Reset Password</CardTitle>
        <CardDescription className='text-sm text-foreground'>
          Don&apos;t have an account?{' '}
          <Link className='font-medium underline' href='/sign-up'>
            Sign up
          </Link>
        </CardDescription>
      </CardHeader>
      <CardContent>
        <Form {...form}>
          <form
            onSubmit={form.handleSubmit(handleForgotPassword)}
            className='flex flex-col min-w-64 space-y-6'
          >
            <FormField
              control={form.control}
              name='email'
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Email</FormLabel>
                  <FormControl>
                    <Input
                      type='email'
                      placeholder='you@example.com'
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <SubmitButton
              disabled={isLoading}
              pendingText='Resetting Password...'
            >
              Reset Password
            </SubmitButton>
            {statusMessage &&
              (statusMessage.includes('Error') ||
              statusMessage.includes('error') ||
              statusMessage.includes('failed') ||
              statusMessage.includes('invalid') ? (
                <StatusMessage message={{ error: statusMessage }} />
              ) : (
                <StatusMessage message={{ success: statusMessage }} />
              ))}
          </form>
        </Form>
      </CardContent>
    </Card>
  );
};
export default ForgotPassword;
