import { useEffect } from 'react';
import PropTypes from 'prop-types';
import { useMemoizedFn, useDebounceFn } from 'ahooks';

function WindowFocusAware({ callback }) {
  const debounceFn = useDebounceFn(callback);
  const handleVisibilityChange = useMemoizedFn(() => {
    if (!document.hidden) {
      debounceFn.run();
    }
  });
  useEffect(() => {
    window.addEventListener('focus', debounceFn.run);
    document.addEventListener('visibilitychange', handleVisibilityChange);
    return () => {
      window.removeEventListener('focus', debounceFn.run);
      document.removeEventListener('visibilitychange', handleVisibilityChange);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  return null;
}

WindowFocusAware.propTypes = {
  callback: PropTypes.func.isRequired,
};

export default WindowFocusAware;
