import { useEffect, useState, useRef } from 'react';
import debounce from 'lodash-es/debounce';
const DEBOUNCE_TIME = 300;

/**
 * Easily gets the width and height of referenced component
 * Example:
 *
 ```
   const buttonWrapperEl = useRef(null);
   const [width, height] = useElementsSize(buttonWrapperEl);
   <button ref={ref}></button>
   <div style={width}></div>
 ```
 * @param {object} ref - The `ref` to measure
 */
export function useElementsSize(ref, checkOnRerender = false) {
  const [size, setSize] = useState({});
  const sizeRef = useRef({});
  const setSizeDebouncedRef = useRef(debounce(setSize, DEBOUNCE_TIME, {
    leading: true
  }));
  sizeRef.current = size;
  useEffect(() => {
    const handleResize = () => {
      if (ref.current) {
        const {
          width,
          height
        } = ref.current.getBoundingClientRect();
        setSize({
          width,
          height
        });
      }
    };
    handleResize();
    const debouncedResize = debounce(handleResize, DEBOUNCE_TIME);
    window.addEventListener('resize', debouncedResize);
    return () => {
      window.removeEventListener('resize', debouncedResize);
      debouncedResize.cancel();
      setSizeDebouncedRef.current?.cancel?.();
    };
  }, []);
  useEffect(() => {
    if (checkOnRerender && ref.current) {
      const {
        width,
        height
      } = ref.current.getBoundingClientRect();
      if (width !== sizeRef.current.width || height !== sizeRef.current.height) {
        setSizeDebouncedRef.current({
          width,
          height
        });
      }
    }
  });
  return [size.width, size.height];
}