import React from 'react'

import uploaderUtils from './uploader-utils'

const { isImageFile, isVideoFile } = uploaderUtils

export default function PreviewThumb({ file, size = 96 }: { file: File; size?: number }) {
  const [url, setUrl] = React.useState<string>()

  React.useEffect(() => {
    const objectUrl = URL.createObjectURL(file)
    setUrl(objectUrl)
    return () => {
      try {
        URL.revokeObjectURL(objectUrl)
      } catch {
        // Ignore revocation races during unmount.
      }
    }
  }, [file])

  if (!url) return null

  const baseStyle: React.CSSProperties = { width: size, height: size, objectFit: 'cover', borderRadius: 12 }
  if (isImageFile(file)) return <img src={url} alt="" style={baseStyle} className="preview-thumb" />
  if (isVideoFile(file)) return <video src={url} muted preload="metadata" playsInline style={baseStyle} className="preview-thumb" />
  return (
    <div style={{ ...baseStyle, display: 'grid', placeItems: 'center' }} className="preview-thumb">
      📄
    </div>
  )
}
