import { ActionCreatorWithPayload } from '@reduxjs/toolkit';
import { ElementType } from 'react';
import { useAppDispatch } from '../../hooks';
import { extractFormData, IndexSignature } from '../../utils';

export const WithHocForm = (
  Component: ElementType,
  formik: boolean = false
) => {
  return function WithHocFormComponent({ ...props }: IndexSignature) {
    const dispatch = useAppDispatch();

    return formik ? (
      <Component
        handleFormikDataChange={(
          values: any,
          setFormData: ActionCreatorWithPayload<any>,
          resetForm: any
        ) => {
          dispatch(setFormData(values));
          resetForm();
        }}
        {...props}
      />
    ) : (
      <Component
        handleFormDataChange={(
          e: any,
          setFormData: ActionCreatorWithPayload<any>
        ) => {
          e.preventDefault();
          dispatch(setFormData(extractFormData(e)));
          e.target.reset();
        }}
        {...props}
      />
    );
  };
};

export type HandleFormDataChangeType = (
  e: any,
  setFormData: ActionCreatorWithPayload<any>
) => void;

export type HandleFormikDataChangeType = (
  values: any,
  setFormData: ActionCreatorWithPayload<any>,
  resetForm: any
) => void;
