import { z } from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form';
import {
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
  Input,
} from '@/components/ui';
import { SubmitButton } from '@/components/default';
import { useState } from 'react';
import { type Result } from '@/lib/actions';
import { StatusMessage } from '@/components/default';

const formSchema = z
  .object({
    password: z.string().min(8, {
      message: 'Password must be at least 8 characters.',
    }),
    confirmPassword: z.string(),
  })
  .refine((data) => data.password === data.confirmPassword, {
    message: 'Passwords do not match.',
    path: ['confirmPassword'],
  });

type ResetPasswordFormProps = {
  onSubmit: (formData: FormData) => Promise<Result<null>>;
  message?: string;
};

export const ResetPasswordForm = ({
  onSubmit,
  message,
}: ResetPasswordFormProps) => {
  const [isLoading, setIsLoading] = useState(false);
  const [statusMessage, setStatusMessage] = useState(message ?? '');

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

  const handleUpdatePassword = async (values: z.infer<typeof formSchema>) => {
    setIsLoading(true);
    try {
      // Convert form values to FormData for your server action
      const formData = new FormData();
      formData.append('password', values.password);
      formData.append('confirmPassword', values.confirmPassword);

      const result = await onSubmit(formData);
      if (result?.success) {
        setStatusMessage('Password updated successfully!');
        form.reset(); // Clear the form on success
      } else {
        setStatusMessage('Error: Unable to update password!');
      }
    } catch (error) {
      setStatusMessage(
        error instanceof Error ? error.message : 'Password was not updated!',
      );
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div>
      <CardHeader className='pb-5'>
        <CardTitle className='text-2xl'>Change Password</CardTitle>
        <CardDescription>
          Update your password to keep your account secure
        </CardDescription>
      </CardHeader>
      <CardContent>
        <Form {...form}>
          <form
            onSubmit={form.handleSubmit(handleUpdatePassword)}
            className='space-y-6'
          >
            <FormField
              control={form.control}
              name='password'
              render={({ field }) => (
                <FormItem>
                  <FormLabel>New Password</FormLabel>
                  <FormControl>
                    <Input type='password' {...field} />
                  </FormControl>
                  <FormDescription>
                    Enter your new password. Must be at least 8 characters.
                  </FormDescription>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name='confirmPassword'
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Confirm Password</FormLabel>
                  <FormControl>
                    <Input type='password' {...field} />
                  </FormControl>
                  <FormDescription>
                    Please re-enter your new password to confirm.
                  </FormDescription>
                  <FormMessage />
                </FormItem>
              )}
            />
            {statusMessage && (
              <div
                className={`text-sm text-center ${
                  statusMessage.includes('Error') ||
                  statusMessage.includes('failed')
                    ? 'text-destructive'
                    : 'text-green-600'
                }`}
              >
                {statusMessage}
              </div>
            )}
            <div className='flex justify-center'>
              <SubmitButton
                disabled={isLoading}
                pendingText='Updating Password...'
              >
                Update Password
              </SubmitButton>
            </div>
          </form>
        </Form>
      </CardContent>
    </div>
  );
};
