/**
 * Form Wrapper - React bridge for vendor form utilities
 *
 * @vendor-dependency @vendor-web/js/patterns/form.js
 * @cleanup-status ⚠️ Pending vendor cleanup support
 */

import React, { useEffect, useRef, ReactNode } from 'react';
import {
  checkboxButtonDisableToggle,
  formErrorMessage,
  formReset,
  formValidation,
} from '@vendor-web/js/patterns/form.js';

type FormWrapperProps = {
  children: ReactNode;
  className?: string;
  /** Selector string passed to vendor form.js (e.g., '.contactForm-form') */
  formSelector: string;
  /** Selector used by vendor form.js to find the submit button */
  submitButtonSelector?: string;
  /** Optional selector for a checkbox that gates the submit button */
  checkboxSelector?: string;
  /** Called when vendor validation succeeds */
  onSuccess?: (data: Record<string, FormDataEntryValue>) => void;
  /** Called when vendor validation fails */
  onError?: (errors: unknown) => void;
  /** Whether to reset form on success (default: true) */
  resetOnSuccess?: boolean;
};

const FormWrapper: React.FC<FormWrapperProps> = ({
  children,
  className = '',
  formSelector,
  submitButtonSelector,
  checkboxSelector,
  onSuccess,
  onError,
  resetOnSuccess = true,
}) => {
  const formRef = useRef<HTMLFormElement>(null);

  useEffect(() => {
    const formElement = formRef.current;
    if (!formElement || !formSelector) return;

    const buttonSelector =
      submitButtonSelector || '[type="submit"], [type="button"]';

    if (checkboxSelector) {
      checkboxButtonDisableToggle({
        buttonSelector,
        checkboxSelector,
      });
    }

    let isUnmounted = false;

    const attachValidation = async () => {
      try {
        const data = await formValidation(formSelector);
        if (isUnmounted) return;

        onSuccess?.(data as Record<string, FormDataEntryValue>);

        if (resetOnSuccess) {
          formReset({
            formSelector,
            checkboxButtonDisableToggle: Boolean(checkboxSelector),
          });
        }
      } catch (error) {
        if (isUnmounted) return;

        formErrorMessage({
          formSelector,
          errorData: error as object,
        });

        onError?.(error);
      }
    };

    attachValidation();

    return () => {
      isUnmounted = true;
      // Vendor form.js does not expose cleanup; awaiting vendor support.
    };
  }, [
    formSelector,
    submitButtonSelector,
    checkboxSelector,
    onSuccess,
    onError,
    resetOnSuccess,
  ]);

  return (
    <form ref={formRef} className={className}>
      {children}
    </form>
  );
};

export default FormWrapper;
