import React, { useRef, useEffect, useState, useCallback } from 'react';
const IntersectionObserver = require('intersection-observer');
import getAgent from '@egjs/agent';

const isIE = getAgent().os.name === 'ie';

const DEFAULT_IMG_SRC = '/static/img/svg/meta_loading.svg';

interface IOwnProps extends React.ImgHTMLAttributes<HTMLImageElement> {
  src: string;
  fallbackSrc?: string;
  setImageRef?: (ref: React.RefObject<HTMLImageElement>) => void;
}

const Img: React.FC<IOwnProps> = ({
  src,
  ...restProps
}) => {
  const imgRef = useRef<HTMLImageElement>(null);
  const isAvailableWindowIO = !!window.IntersectionObserver;

  const lazyLoadImage = useCallback<IntersectionObserverCallback>(
    (entries: IntersectionObserverEntry[], observer: IntersectionObserver) => {
      entries.forEach((entry: any) => {
        const { target } = entry;

        if (entry.isIntersecting && imgRef && imgRef.current && imgRef.current.parentElement) {
          const parentElement = imgRef.current.parentElement;

          target.src = target.dataset.src;
          parentElement.dataset.isLoaded = 'true';
          observer.unobserve(target);
        }
      });
    },
    [],
  );

  useEffect(() => {
    if (isAvailableWindowIO) {
      // IE11 경우 lazyload 오류 발생.
      if (isIE) {
        return;
      }

      if (imgRef.current) {
        const lazyLoadingIO: IntersectionObserver = isAvailableWindowIO
          ? new window.IntersectionObserver(lazyLoadImage)
          : IntersectionObserver(lazyLoadImage);

        lazyLoadingIO.observe(imgRef.current);
      }
    }
  }, [imgRef]);

  const [isError, setIsError] = useState(false);

  const onError = (e: any) => {
    setIsError(true);
    restProps.onError?.(e);
  };

  return isError ? (
    <img src={src} {...restProps} />
  ) : (
    <img
      ref={imgRef}
      src={DEFAULT_IMG_SRC}
      data-src={src}
      onError={onError}
      {...restProps}
    />
  );
};

export default Img;
