'use client'

import { useState, useEffect } from 'react'
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import { cn, getInitials } from '@/lib/utils'
import { Camera } from 'lucide-react'

type UserAvatarProps = {
  user: {
    name?: string | null
    email?: string | null
    profileImageKey?: string | null
  }
  size?: 'xs' | 'sm' | 'md' | 'lg' | 'xl' | '2xl'
  className?: string
  showEditOverlay?: boolean
  avatarUrl?: string | null
}

const sizeClasses = {
  xs: 'h-6 w-6',
  sm: 'h-8 w-8',
  md: 'h-10 w-10',
  lg: 'h-12 w-12',
  xl: 'h-16 w-16',
  '2xl': 'h-24 w-24',
}

const textSizeClasses = {
  xs: 'text-[10px]',
  sm: 'text-xs',
  md: 'text-sm',
  lg: 'text-base',
  xl: 'text-lg',
  '2xl': 'text-2xl',
}

const iconSizeClasses = {
  xs: 'h-3 w-3',
  sm: 'h-3 w-3',
  md: 'h-4 w-4',
  lg: 'h-5 w-5',
  xl: 'h-6 w-6',
  '2xl': 'h-8 w-8',
}

export function UserAvatar({
  user,
  size = 'md',
  className,
  showEditOverlay = false,
  avatarUrl,
}: UserAvatarProps) {
  const [imageError, setImageError] = useState(false)
  const initials = getInitials(user.name || user.email || 'U')

  // Reset error state when avatarUrl changes
  useEffect(() => {
    setImageError(false)
  }, [avatarUrl])

  return (
    <div className={cn('relative group', className)}>
      <Avatar className={cn(sizeClasses[size])}>
        {avatarUrl && !imageError ? (
          <AvatarImage
            src={avatarUrl}
            alt={user.name || 'User avatar'}
            onError={() => setImageError(true)}
          />
        ) : null}
        <AvatarFallback className={cn(textSizeClasses[size])}>
          {initials}
        </AvatarFallback>
      </Avatar>

      {showEditOverlay && (
        <div
          className={cn(
            'absolute inset-0 flex items-center justify-center rounded-full',
            'bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity',
            'cursor-pointer'
          )}
        >
          <Camera className={cn('text-white', iconSizeClasses[size])} />
        </div>
      )}
    </div>
  )
}
