import { clsx } from 'clsx';
import { useRef } from 'react';

import { useHasIntersected } from '../common/hooks';

export interface ImageProps {
  alt: string;
  src: string;
  id?: string;
  onLoad?: () => void;
  onError?: () => void;
  className?: string;
  loading?: 'lazy' | 'eager';
  stretch?: boolean;
  role?: string;
  shrink?: boolean;
}

export const EmptyTransparentImage =
  'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';

const Image = ({
  id,
  src,
  alt,
  onLoad,
  onError,
  className,
  loading,
  stretch = true,
  role,
  shrink = true,
}: ImageProps) => {
  const elementReference = useRef<HTMLImageElement>(null);
  const [hasIntersected] = useHasIntersected({ elRef: elementReference, loading });
  let imageSource = src;
  let imageOnLoad = onLoad;

  if (loading === 'lazy' && !hasIntersected) {
    imageSource = EmptyTransparentImage;
    imageOnLoad = undefined;
  }

  return (
    <img
      ref={elementReference}
      id={id}
      alt={alt}
      src={imageSource}
      className={clsx([
        'tw-image',
        {
          'tw-image__stretch': stretch,
          'tw-image__shrink': shrink,
        },
        className,
      ])}
      role={role}
      onLoad={imageOnLoad}
      onError={onError}
    />
  );
};

export default Image;
