import { getUniqueFormikErrors } from '@/lib/formik-helper';
import { FormikProps } from 'formik';
import { useState } from 'react';

interface UseFormikErrorListOptions {
  onBeforeSubmit?: (e: React.FormEvent<HTMLFormElement>) => boolean | void;
  onAfterValidation?: () => void | Promise<void>;
  onAfterSubmit?: () => void | Promise<void>;
}

export const useFormikErrorList = <T>(
  formik: FormikProps<T>,
  options?: UseFormikErrorListOptions
) => {
  const [formErrorList, setFormErrorList] = useState<string[]>([]);

  const handleValidateForm = async () => {
    const errors = await formik.validateForm();

    if (Object.keys(errors).length > 0) {
      const errorMessages = getUniqueFormikErrors(errors);
      setFormErrorList(errorMessages);
      return false;
    }

    return true;
  };

  const handleFormSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();

    // Call onBeforeSubmit callback
    if (options?.onBeforeSubmit) {
      const shouldContinue = options.onBeforeSubmit(e);
      if (shouldContinue === false) {
        return; // Cancel submit
      }
    }

    // Validate form
    const isValid = await handleValidateForm();
    if (isValid) {
      close();
    }

    // Call onAfterValidation callback if validation passed
    if (options?.onAfterValidation) {
      await options.onAfterValidation();
    }

    // Submit form
    formik.handleSubmit();

    // Call onAfterSubmit callback if validation passed
    if (options?.onAfterSubmit) {
      await options.onAfterSubmit();
    }
  };

  const close = () => {
    setFormErrorList([]);
  };

  return {
    formErrorList,
    setFormErrorList,
    close,
    handleValidateForm,
    handleFormSubmit,
  };
};
