import React, { useCallback, useEffect, useRef } from 'react';
import { useFormikContext } from 'formik';
import { debounce, isEqual } from 'lodash';

const propTypes = {};

export default function AutoSave( { delay } ) {
	const formik = useFormikContext();
	const prevValues = useRef( null );

	const { meta, ...valueWithoutMeta } = formik.values;

	const debouncedSubmit = useCallback(
		debounce( () => {
			formik.submitForm( valueWithoutMeta ).then( () => {
				prevValues.current = valueWithoutMeta;
			} );
		}, delay ),
		[ delay, formik.submitForm ]
	);

	useEffect( () => {
		if (
			formik.dirty &&
			! isEqual( valueWithoutMeta, prevValues.current )
		) {
			debouncedSubmit();
		}
		return debouncedSubmit.clear;
	}, [
		debouncedSubmit,
		valueWithoutMeta,
		prevValues.current,
		formik.isSubmitting,
		formik.isValidating,
	] );

	return <></>;
}

AutoSave.propTypes = propTypes;
