/**
 * Custom Image
 *
 * @module CustomImage
 */
import React, { memo, useCallback, useEffect, useRef, useState } from "react";

import classNames from "classnames";

import css from "./CustomImage.module.less";
import defaultImageItem from "../../../assets/images/img-thumb-empty-144@3x.png";

//animationSpeed : "slow", "normal",  "fast", "none"   ==> 500ms, 250ms, 10ms, 0ms
export default memo(function CustomImage({
  src,
  className,
  hide,
  delay = 0,
  animationSpeed = "fast",
  onLoad,
  onError,
  alt,
  ariaLabel,
  fallbackSrc,
}) {
  const [imageLoaded, setImageLoaded] = useState(false);
  const [imgSrc, setImgSrc] = useState(src);
  const [error, setError] = useState(false);

  const showImageJob = useRef(null);

  useEffect(() => {
    const _src = Array.isArray(src) ? src[0] : src;
    if (_src && _src !== imgSrc) {
      if (showImageJob.current) {
        clearTimeout(showImageJob.current);
        showImageJob.current = null;
      }
      setImgSrc(_src);
      setError(false);
      setImageLoaded(false);
    }
    if (!_src) {
      setError(true);
    }
  }, [src]);

  useEffect(() => {
    return () => {
      if (showImageJob.current) {
        clearTimeout(showImageJob.current);
        showImageJob.current = null;
      }
    };
  }, []);

  const _onLoad = useCallback(() => {
    if (showImageJob.current) {
      clearTimeout(showImageJob.current);
    }
    showImageJob.current = setTimeout(() => {
      setImageLoaded(true);
    }, delay);
    if (onLoad) onLoad();
  }, [onLoad, delay]);

  const _onError = useCallback(() => {
    setError(true);
    if (onError) onError();
  }, [onError]);

  if (error) {
    return (
      <img
        className={classNames(css.customimage, className, css.error)}
        src={fallbackSrc || defaultImageItem}
        alt=""
      />
    );
  }
  if (!imgSrc || !src) {
    return null;
  }
  return (
    <img
      className={classNames(
        css.customimage,
        className,
        !imageLoaded || hide ? css.hidden : null,
        css[animationSpeed]
      )}
      src={imgSrc}
      onLoad={_onLoad}
      onError={_onError}
      alt={alt}
      aria-label={ariaLabel}
      loading="lazy"
    />
  );
});
