import { useEffect, useState, type ImgHTMLAttributes } from 'react';

type AppImageProps = Omit<ImgHTMLAttributes<HTMLImageElement>, 'src'> & {
  src?: string | null;
  wrapperClassName?: string;
  fit?: 'cover' | 'contain';
};

export default function AppImage({
  src,
  alt = '',
  className = '',
  wrapperClassName = '',
  fit = 'cover',
  ...rest
}: AppImageProps) {
  const [loaded, setLoaded] = useState(false);
  const [failed, setFailed] = useState(false);
  const hasSrc = Boolean(src);

  useEffect(() => {
    setLoaded(false);
    setFailed(!src);
  }, [src]);

  const showPlaceholder = !hasSrc || failed || !loaded;

  return (
    <div className={`app-image${wrapperClassName ? ` ${wrapperClassName}` : ''}`}>
      {showPlaceholder && (
        <div className="app-image-placeholder" aria-hidden>
          {hasSrc && !failed ? (
            <span className="app-image-spinner" />
          ) : (
            <span className="material-symbols-outlined app-image-fallback-icon">image</span>
          )}
        </div>
      )}
      {hasSrc && !failed && (
        <img
          {...rest}
          src={src!}
          alt={alt}
          className={`app-image-img app-image-img--${fit}${loaded ? ' is-loaded' : ''}${className ? ` ${className}` : ''}`}
          onLoad={() => setLoaded(true)}
          onError={() => {
            setFailed(true);
            setLoaded(false);
          }}
        />
      )}
    </div>
  );
}
