import React, { useEffect, useRef } from 'react';

type Props = {
  onClick: (e: MouseEvent | TouchEvent) => void;
  children: React.ReactNode;
};

const ClickAwayListener: React.FC<Props> = ({
  onClick,
  children,
  ...rest
}: Props) => {
  const node = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handleClick = (e: MouseEvent | TouchEvent) => {
      if (node.current && node.current.contains(e.target as HTMLElement)) {
        return;
      }

      onClick(e);
    };

    document.addEventListener('mousedown', handleClick);
    document.addEventListener('touchstart', handleClick);

    return () => {
      document.removeEventListener('mousedown', handleClick);
      document.removeEventListener('touchstart', handleClick);
    };
  }, [onClick]);

  return (
    <div ref={node} {...rest}>
      {children}
    </div>
  );
};

export default ClickAwayListener;
