import React, { useEffect, useState } from 'react'
import { View } from '../view'

/**
 * Thumbnail preview for a local {@link File} via FileReader (data URL).
 *
 * @param {{ file: File, size?: string, style?: import('react').CSSProperties }} props
 */
export function LocalFilePreview({ file, size = '32px', style = {} }) {
  const [src, setSrc] = useState(undefined)

  useEffect(() => {
    if (!file) {
      setSrc(undefined)
      return
    }
    const reader = new FileReader()
    reader.onload = e => setSrc(e.target?.result)
    reader.readAsDataURL(file)
  }, [file])

  if (!file) return null

  const isImage = file.type?.startsWith('image/')

  if (!isImage) {
    return (
      <View
        width={size}
        height={size}
        style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          borderRadius: 'var(--space-s)',
          background: 'var(--color-secondary)',
          fontSize: 10,
          overflow: 'hidden',
          ...style,
        }}
        aria-hidden
      >
        {file.name?.slice(0, 3) || '?'}
      </View>
    )
  }

  return (
    <View
      as="img"
      src={src}
      alt=""
      width={size}
      height={size}
      style={{
        objectFit: 'cover',
        borderRadius: 'var(--space-s)',
        background: 'var(--color-secondary)',
        ...style,
      }}
    />
  )
}
