'use client'

import { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/avatar'
import { cn } from '@/lib/utils'

interface User {
  id: string
  avatar?: string | null
}

interface Organization {
  id: string
  name?: string | null
  fullName?: string | null
  users?: User[]
}

interface OrganizationAvatarProps {
  organization: Organization
  size?: 'sm' | 'md' | 'lg'
  className?: string
}

// Цвета для fallback аватарок
const FALLBACK_COLORS = [
  'bg-blue-500',
  'bg-green-500',
  'bg-purple-500',
  'bg-orange-500',
  'bg-pink-500',
  'bg-indigo-500',
  'bg-teal-500',
  'bg-red-500',
  'bg-yellow-500',
  'bg-cyan-500',
]

function getInitials(name: string): string {
  return name
    .split(' ')
    .map((word) => word.charAt(0))
    .join('')
    .toUpperCase()
    .slice(0, 2)
}

function getColorForOrganization(organizationId: string): string {
  const hash = organizationId.split('').reduce((acc, char) => acc + char.charCodeAt(0), 0)
  return FALLBACK_COLORS[hash % FALLBACK_COLORS.length]
}

function getSizes(size: 'sm' | 'md' | 'lg') {
  switch (size) {
    case 'sm':
      return { avatar: 'size-8', text: 'text-xs' }
    case 'md':
      return { avatar: 'size-10', text: 'text-sm' }
    case 'lg':
      return { avatar: 'size-12', text: 'text-base' }
    default:
      return { avatar: 'size-8', text: 'text-xs' }
  }
}

export function OrganizationAvatar({ organization, size = 'md', className }: OrganizationAvatarProps) {
  // Берем аватарку первого пользователя организации
  const userAvatar = organization.users?.[0]?.avatar

  // Получаем имя для инициалов
  const displayName = organization.name || organization.fullName || 'Организация'
  const initials = getInitials(displayName)

  // Получаем цвет для fallback
  const fallbackColor = getColorForOrganization(organization.id)

  const sizes = getSizes(size)

  return (
    <Avatar className={cn(sizes.avatar, className)}>
      {userAvatar && <AvatarImage src={userAvatar} alt={displayName} />}
      <AvatarFallback className={cn(fallbackColor, 'text-white font-medium', sizes.text)}>{initials}</AvatarFallback>
    </Avatar>
  )
}
