import * as React from 'react'
import { useEffect, useRef, useState } from 'react'
import Avatar from '@mui/material/Avatar'
import type { SxProps, Theme } from '@mui/material/styles'
import { createAvatar } from '@dicebear/core'
import { DEFAULT_STYLE_ID, loadAvatarStyle } from '@/shared/lib/avatar-styles'

type UserAvatarProps = {
  userId: string
  avatarUrl?: string | null
  avatarStyle?: string | null
  size?: number
  sx?: SxProps<Theme>
}

export const UserAvatar = React.memo(function UserAvatar({
  userId,
  avatarUrl,
  avatarStyle,
  size = 40,
  sx,
}: UserAvatarProps) {
  const [generatedSrc, setGeneratedSrc] = useState<string | null>(null)
  const styleId = avatarStyle || DEFAULT_STYLE_ID
  const styleIdRef = useRef(styleId)

  useEffect(() => {
    let cancelled = false
    styleIdRef.current = styleId

    loadAvatarStyle(styleId).then((style) => {
      if (!cancelled && styleIdRef.current === styleId) {
        const avatar = createAvatar(style, { seed: userId })
        setGeneratedSrc(avatar.toDataUri())
      }
    })

    return () => {
      cancelled = true
    }
  }, [userId, styleId])

  const src = avatarUrl || generatedSrc || ''

  return (
    <Avatar src={src} alt="" sx={{ width: size, height: size, bgcolor: 'primary.main', ...sx }}>
      {!src && '?'}
    </Avatar>
  )
})
