import type { BaseSyntheticEvent } from 'react'
import { useCallback } from 'react'

import styled from 'styled-components/macro'

const ImageStyled = styled.img``

type Props = {
  alt?: string,
  className?: string,
  fallbackSrc?: string,
  onLoad?: () => void,
  src: string,
  title?: string,
}

export const Image = ({
  alt,
  className,
  fallbackSrc = '',
  onLoad,
  src,
  title,
}: Props) => {
  const onError = useCallback((e: BaseSyntheticEvent) => {
    // eslint-disable-next-line no-param-reassign
    e.target.onError = ''
    // eslint-disable-next-line no-param-reassign
    e.target.src = fallbackSrc
  }, [fallbackSrc])

  return (
    <ImageStyled
      alt={alt}
      src={src}
      className={className}
      onError={onError}
      onLoad={onLoad}
      title={title}
    />
  )
}
