import { PropsWithChildren, useEffect, useState } from 'react'
import { Image, Text, View } from '@tarojs/components'
import './index.scss'

interface AvatarProps {
  avatarKey?: string
  avatarUrl?: string
  label?: string
  size?: 'sm' | 'md' | 'lg' | 'xl'
  online?: boolean
  petTag?: string
}

export function Avatar({
  avatarKey = 'gradient-avatar-1',
  avatarUrl,
  label,
  size = 'md',
  online = false,
  petTag,
  children
}: PropsWithChildren<AvatarProps>) {
  // Gracefully fall back to the gradient if the temp URL fails to load (e.g. a
  // 403 from storage permissions, or an expired signed URL).
  const [failed, setFailed] = useState(false)
  useEffect(() => setFailed(false), [avatarUrl])
  const hasImage = Boolean(avatarUrl && !avatarUrl.startsWith('cloud://')) && !failed
  return (
    <View className={`avatar avatar--${size} ${hasImage ? 'avatar--image' : avatarKey}`}>
      {hasImage ? (
        <Image className='avatar__image' src={avatarUrl as string} mode='aspectFill' onError={() => setFailed(true)} />
      ) : (
        children || (label ? <Text className='avatar__label'>{label.slice(0, 1)}</Text> : null)
      )}
      {online ? <View className='avatar__online' /> : null}
      {petTag ? <Text className='avatar__pet-tag'>{petTag}</Text> : null}
    </View>
  )
}

export default Avatar
