/* eslint-disable jsx-a11y/alt-text */
/* eslint-disable jsx-a11y/no-noninteractive-element-interactions */
import {ImgHTMLAttributes, useCallback, useMemo, memo, useState} from 'react'

import {cn} from '../../lib/utils'
import {getThumbhashDataURL, getResizedImageUrl} from '../../utils'

type ImageProps = ImgHTMLAttributes<HTMLImageElement> & {
  src?: string
  thumbhash?: string | null
  aspectRatio?: number | string
}

export const Image = memo(function Image(props: ImageProps) {
  const {
    src,
    thumbhash,
    onLoad,
    className,
    style,
    aspectRatio = 'auto',
    ...restProps
  } = props

  const [isLoaded, setIsLoaded] = useState(false)

  const thumbhashDataURL = useMemo(
    () => getThumbhashDataURL(thumbhash ?? undefined),
    [thumbhash]
  )

  const handleLoad = useCallback(
    (event: React.SyntheticEvent<HTMLImageElement, Event>) => {
      setIsLoaded(true)
      onLoad?.(event)
    },
    [onLoad]
  )

  const resizedImageSrc = useMemo(() => getResizedImageUrl(src), [src])

  return (
    <div
      className={cn('relative w-full ', className)}
      style={{
        ...style,
        aspectRatio,
        backgroundImage: thumbhashDataURL
          ? `url(${thumbhashDataURL})`
          : undefined,
        backgroundSize: 'cover',
        backgroundPosition: 'center',
      }}
    >
      <img
        className={cn(
          'absolute inset-0 opacity-0 object-cover',
          isLoaded && 'opacity-100'
        )}
        src={resizedImageSrc}
        onLoad={handleLoad}
        {...restProps}
      />
    </div>
  )
})
