import React, { useEffect, useState } from 'react'
import Skeleton from 'react-loading-skeleton'
import 'react-loading-skeleton/dist/skeleton.css'
import './DraftItemThumbnail.scss'

const DraftItemThumbnail = ({ src, onClick, disabled }) => {
  const [imageLoaded, setImageLoaded] = useState(false)
  const [imageError, setImageError] = useState(false)

  useEffect(() => {
    setImageLoaded(false)
    setImageError(false)
  }, [src])

  const handleClick = () => {
    if (!disabled && onClick) {
      onClick()
    }
  }

  const handleKeyDown = (e) => {
    if (e.key === 'Enter' && !disabled && onClick) {
      onClick()
    }
  }

  const handleImageLoad = () => {
    setImageLoaded(true)
    setImageError(false)
  }

  const handleImageError = () => {
    setImageError(true)
    setImageLoaded(false)
  }

  return (
    <div
      className={`draft-item-thumbnail ${disabled ? 'disabled' : ''}`}
      onClick={handleClick}
      onKeyDown={handleKeyDown}
      role="button"
      tabIndex={disabled ? -1 : 0}
    >
      {src ? (
        <>
          {(!imageLoaded || imageError) && (
            <Skeleton width={120} height={120} />
          )}
          <img
            src={src}
            alt=""
            className={`thumbnail-image ${imageLoaded && !imageError ? '' : 'hide'}`}
            onLoad={handleImageLoad}
            onError={handleImageError}
          />
        </>
      ) : (
        <Skeleton width={120} height={120} />
      )}
    </div>
  )
}

export default DraftItemThumbnail
