import { useState } from 'react'
import { makeStyles, mergeClasses } from '@fluentui/react-components'
import { VideoClipRegular, MusicNote2Regular } from '@fluentui/react-icons'
import type { MediaKind } from '@shared/ipc'
import { useResolvedDark } from '../store/systemTheme'
import { thumbColors } from '../lib/theme'

const useStyles = makeStyles({
  box: {
    flexShrink: 0,
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    overflow: 'hidden'
  },
  img: {
    width: '100%',
    height: '100%',
    objectFit: 'cover',
    display: 'block'
  }
})

/**
 * A media preview thumbnail: shows the image at `src` when one is available and
 * loads, otherwise a kind icon on a quiet neutral tint (the same palette the
 * placeholders used before). The load failure is tracked per-src, so a thumbnail
 * that arrives later (e.g. resolved after a probe) is retried rather than left on
 * the fallback. The caller sizes the box via `className` (width/height/radius).
 */
export function MediaThumb({
  src,
  kind,
  iconSize = 24,
  className
}: {
  src?: string
  kind: MediaKind
  iconSize?: number
  className?: string
}): React.JSX.Element {
  const styles = useStyles()
  const isDark = useResolvedDark()
  const colors = thumbColors[isDark ? 'dark' : 'light'][kind]
  const [failedSrc, setFailedSrc] = useState<string | null>(null)
  const showImg = !!src && failedSrc !== src

  // The neutral tint always backs the box, so there's a placeholder behind the
  // image while it loads (and the kind icon stays legible when there's no image).
  return (
    <div
      className={mergeClasses(styles.box, className)}
      style={{ backgroundColor: colors.bg, color: colors.fg }}
    >
      {showImg ? (
        <img className={styles.img} src={src} alt="" onError={() => setFailedSrc(src ?? null)} />
      ) : kind === 'audio' ? (
        <MusicNote2Regular fontSize={iconSize} />
      ) : (
        <VideoClipRegular fontSize={iconSize} />
      )}
    </div>
  )
}
