import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form';
import { useRef } from 'react';
import ReCAPTCHA from 'react-google-recaptcha';
import { ContactFormSchema, contactFormSchema } from '@/src/types/contact';
import { useApiWithToast } from '@/src/hooks/useApiWithToast';
import { usePathname } from 'next/navigation';

export const useContactFormBase = () => {
  const { handle } = useApiWithToast();
  const recaptchaRef = useRef<ReCAPTCHA>(null);
  const pathname = usePathname();
  const isBuilder = pathname.includes('/portfolios/');

  const form = useForm<ContactFormSchema>({
    resolver: zodResolver(contactFormSchema),
    defaultValues: { name: '', email: '', message: '' },
  });

  const onSubmit = async (values: ContactFormSchema) => {
    const token = await recaptchaRef.current?.executeAsync();
    const response = await handle(
      fetch('/api/send', {
        method: 'POST',
        body: JSON.stringify({ ...values, recaptchaToken: token }),
      })
    );
    if (response) {
      form.reset();
    }
  };

  return { form, onSubmit, recaptchaRef, isBuilder };
};
