import React from 'react'

import styles from './_image.module.scss'
import Icon from '../Icons/Icon'
import { type IconSizes } from '../Icons/Icon.models'

export type ImageProps = {
  /** text displayed if the image fails to load */
  alt?: string
  /** custom class for image container */
  containerClass?: string
  /** change the default size of the no-image icon (in px format, ex: '20px') */
  iconSize?:
    | string
    | {
        height: string
        width: string
      }
  /** custom class for image <img> component */
  imageClass?: string
  /** object with styles to overwrite image container default styles */
  style?: React.CSSProperties
  /** object with styles to overwrite image default styles */
  imgStyle?: React.CSSProperties
  /** link to image */
  url?: string
  /** Optional prop to add a test id to the Image for QA testing */
  qaTestId?: string
}

const Image = ({
  alt = 'Product',
  containerClass = '',
  iconSize = '40px',
  imageClass = '',
  style = {},
  imgStyle = {},
  url,
  qaTestId = 'image',
}: ImageProps): React.JSX.Element => {
  const setFallback = (err: React.SyntheticEvent<HTMLImageElement, Event>) => {
    err.currentTarget.onerror = null
    err.currentTarget.src = 'https://images.pattern.com/library/bad-image.svg'
    err.currentTarget.alt = 'No Image'
    err.currentTarget.style.height =
      typeof iconSize === 'object' ? iconSize.height : iconSize
  }

  return (
    <div
      className={`${styles.display} ${styles.thumbnail} ${containerClass}`}
      style={{ ...style }}
      data-testid='image'
      qa-test-id={qaTestId}
    >
      {url ? (
        <img
          className={imageClass}
          src={url}
          onError={setFallback}
          alt={alt}
          style={{ maxWidth: '100%', maxHeight: '100%', ...imgStyle }}
        />
      ) : (
        <Icon icon='picture' iconSize={iconSize as IconSizes} />
      )}
    </div>
  )
}

export default Image
