"use client"

import { useState, useMemo } from "react"
import { motion } from "framer-motion"

// Professional avatar patterns
const AVATAR_PATTERNS = [
  {
    id: 'geometric',
    name: 'Geometric',
    background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
    pattern: (
      <svg className="w-full h-full" viewBox="0 0 100 100" fill="none">
        <circle cx="25" cy="25" r="8" fill="rgba(255,255,255,0.2)" />
        <circle cx="75" cy="25" r="6" fill="rgba(255,255,255,0.15)" />
        <circle cx="25" cy="75" r="6" fill="rgba(255,255,255,0.15)" />
        <circle cx="75" cy="75" r="8" fill="rgba(255,255,255,0.2)" />
        <circle cx="50" cy="50" r="12" fill="rgba(255,255,255,0.1)" />
      </svg>
    )
  },
  {
    id: 'floral',
    name: 'Floral',
    background: 'linear-gradient(135deg, #11998e 0%, #38ef7d 100%)',
    pattern: (
      <svg className="w-full h-full" viewBox="0 0 100 100" fill="none">
        <path d="M50 30 C40 40, 40 60, 50 70 C60 60, 60 40, 50 30 Z" fill="rgba(255,255,255,0.2)" />
        <path d="M30 50 C40 40, 60 40, 70 50 C60 60, 40 60, 30 50 Z" fill="rgba(255,255,255,0.2)" />
        <circle cx="50" cy="50" r="8" fill="rgba(255,255,255,0.3)" />
      </svg>
    )
  },
  {
    id: 'wave',
    name: 'Wave',
    background: 'linear-gradient(135deg, #9f7aea 0%, #667eea 100%)',
    pattern: (
      <svg className="w-full h-full" viewBox="0 0 100 100" fill="none">
        <path d="M0 40 Q25 20, 50 40 T100 40 V100 H0 V40" fill="rgba(255,255,255,0.2)" />
        <path d="M0 60 Q25 40, 50 60 T100 60 V100 H0 V60" fill="rgba(255,255,255,0.15)" />
      </svg>
    )
  },
  {
    id: 'minimal',
    name: 'Minimal',
    background: 'linear-gradient(135deg, #74b9ff 0%, #0984e3 100%)',
    pattern: (
      <svg className="w-full h-full" viewBox="0 0 100 100" fill="none">
        <rect x="20" y="20" width="60" height="2" rx="1" fill="rgba(255,255,255,0.2)" />
        <rect x="25" y="30" width="50" height="2" rx="1" fill="rgba(255,255,255,0.15)" />
        <rect x="30" y="40" width="40" height="2" rx="1" fill="rgba(255,255,255,0.1)" />
        <rect x="25" y="60" width="50" height="2" rx="1" fill="rgba(255,255,255,0.15)" />
        <rect x="20" y="70" width="60" height="2" rx="1" fill="rgba(255,255,255,0.2)" />
      </svg>
    )
  }
]

// Professional emoji sets
const PROFESSIONAL_EMOJIS = {
  business: ['👨‍💼', '👩‍💼', '🧑‍💼', '👔', '💼'],
  creative: ['🎨', '✨', '🌟', '💡', '🎭'],
  tech: ['👨‍💻', '👩‍💻', '🧑‍💻', '💻', '⚡'],
  nature: ['🌱', '🌿', '🍃', '🌸', '🌺'],
  abstract: ['🔮', '💎', '⭐', '🎪', '🎯']
}

// Generate initials from name
const getInitials = (name) => {
  if (!name) return '?'
  return name
    .split(' ')
    .map(word => word.charAt(0).toUpperCase())
    .slice(0, 2)
    .join('')
}

// Generate consistent pattern based on name/email
const getPatternFromString = (str) => {
  if (!str) return AVATAR_PATTERNS[0]
  let hash = 0
  for (let i = 0; i < str.length; i++) {
    hash = str.charCodeAt(i) + ((hash << 5) - hash)
  }
  return AVATAR_PATTERNS[Math.abs(hash) % AVATAR_PATTERNS.length]
}

// Generate consistent emoji based on name/email
const getEmojiFromString = (str, category = 'business') => {
  if (!str) return PROFESSIONAL_EMOJIS[category][0]
  let hash = 0
  for (let i = 0; i < str.length; i++) {
    hash = str.charCodeAt(i) + ((hash << 5) - hash)
  }
  const emojis = PROFESSIONAL_EMOJIS[category] || PROFESSIONAL_EMOJIS.business
  return emojis[Math.abs(hash) % emojis.length]
}

export default function ProfessionalAvatar({
  src,
  name = '',
  email = '',
  size = 'md', // xs, sm, md, lg, xl
  type = 'initials', // initials, emoji, pattern
  emojiCategory = 'business',
  showOnlineStatus = false,
  isOnline = false,
  animated = true,
  className = '',
  onClick,
  ...props
}) {
  const [imageError, setImageError] = useState(false)
  const [imageLoaded, setImageLoaded] = useState(false)

  // Size configurations
  const sizeConfig = {
    xs: { container: 'w-6 h-6', text: 'text-xs', emoji: 'text-xs' },
    sm: { container: 'w-8 h-8', text: 'text-sm', emoji: 'text-sm' },
    md: { container: 'w-10 h-10', text: 'text-base', emoji: 'text-base' },
    lg: { container: 'w-12 h-12', text: 'text-lg', emoji: 'text-lg' },
    xl: { container: 'w-16 h-16', text: 'text-xl', emoji: 'text-2xl' }
  }

  const config = sizeConfig[size] || sizeConfig.md

  // Memoized values for consistency
  const pattern = useMemo(() => getPatternFromString(name || email), [name, email])
  const emoji = useMemo(() => getEmojiFromString(name || email, emojiCategory), [name, email, emojiCategory])
  const initials = useMemo(() => getInitials(name), [name])

  const handleImageError = () => {
    setImageError(true)
  }

  const handleImageLoad = () => {
    setImageLoaded(true)
  }

  const renderFallback = () => {
    switch (type) {
      case 'emoji':
        return (
          <div 
            className={`${config.container} rounded-full flex items-center justify-center text-white relative overflow-hidden`}
            style={{ background: pattern.background }}
          >
            <div className="absolute inset-0">
              {pattern.pattern}
            </div>
            <span className={`${config.emoji} relative z-10`}>
              {emoji}
            </span>
          </div>
        )

      case 'pattern':
        return (
          <div 
            className={`${config.container} rounded-full flex items-center justify-center text-white relative overflow-hidden`}
            style={{ background: pattern.background }}
          >
            <div className="absolute inset-0">
              {pattern.pattern}
            </div>
            <span className={`${config.text} font-semibold relative z-10`}>
              {initials}
            </span>
          </div>
        )

      default: // initials
        return (
          <div 
            className={`${config.container} rounded-full flex items-center justify-center text-white font-semibold shadow-lg`}
            style={{ background: pattern.background }}
          >
            <span className={config.text}>
              {initials}
            </span>
          </div>
        )
    }
  }

  return (
    <motion.div
      initial={animated ? { scale: 0.8, opacity: 0 } : false}
      animate={animated ? { scale: 1, opacity: 1 } : false}
      whileHover={animated ? { scale: 1.05 } : false}
      whileTap={animated ? { scale: 0.95 } : false}
      className={`relative inline-block cursor-pointer ${className}`}
      onClick={onClick}
      {...props}
    >
      {/* Avatar container */}
      <div className="relative">
        {src && !imageError ? (
          <div className={`${config.container} rounded-full overflow-hidden ring-2 ring-white shadow-lg`}>
            {/* Loading placeholder */}
            {!imageLoaded && (
              <div 
                className="absolute inset-0 flex items-center justify-center"
                style={{ background: pattern.background }}
              >
                <motion.div
                  animate={{ rotate: 360 }}
                  transition={{ duration: 1, repeat: Infinity, ease: "linear" }}
                  className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full"
                />
              </div>
            )}
            
            {/* Actual image */}
            <img
              src={src}
              alt={name || 'Avatar'}
              onError={handleImageError}
              onLoad={handleImageLoad}
              className={`w-full h-full object-cover transition-opacity duration-300 ${
                imageLoaded ? 'opacity-100' : 'opacity-0'
              }`}
            />
          </div>
        ) : (
          renderFallback()
        )}

        {/* Online status indicator */}
        {showOnlineStatus && (
          <motion.div
            initial={animated ? { scale: 0 } : false}
            animate={animated ? { scale: 1 } : false}
            className={`absolute -bottom-1 -right-1 w-3 h-3 rounded-full border-2 border-white shadow-sm ${
              isOnline ? 'bg-green-500' : 'bg-gray-400'
            }`}
          >
            {isOnline && (
              <motion.div
                animate={{ scale: [1, 1.2, 1] }}
                transition={{ duration: 2, repeat: Infinity }}
                className="w-full h-full bg-green-400 rounded-full opacity-75"
              />
            )}
          </motion.div>
        )}
      </div>

      {/* Hover tooltip */}
      {name && (
        <div className="absolute -top-8 left-1/2 transform -translate-x-1/2 bg-gray-900 text-white text-xs px-2 py-1 rounded opacity-0 group-hover:opacity-100 transition-opacity duration-200 pointer-events-none whitespace-nowrap">
          {name}
        </div>
      )}
    </motion.div>
  )
}

// Utility components
export const AvatarGroup = ({ 
  avatars = [], 
  max = 4, 
  size = 'md',
  showCount = true,
  className = '',
  ...props 
}) => {
  const visibleAvatars = avatars.slice(0, max)
  const remainingCount = Math.max(0, avatars.length - max)

  const sizeConfig = {
    xs: { container: 'w-6 h-6', text: 'text-xs', spacing: '-space-x-1' },
    sm: { container: 'w-8 h-8', text: 'text-sm', spacing: '-space-x-2' },
    md: { container: 'w-10 h-10', text: 'text-base', spacing: '-space-x-2' },
    lg: { container: 'w-12 h-12', text: 'text-lg', spacing: '-space-x-3' },
    xl: { container: 'w-16 h-16', text: 'text-xl', spacing: '-space-x-4' }
  }

  const config = sizeConfig[size] || sizeConfig.md

  return (
    <div className={`flex items-center ${config.spacing} ${className}`} {...props}>
      {visibleAvatars.map((avatar, index) => (
        <ProfessionalAvatar
          key={index}
          size={size}
          animated={false}
          className="ring-2 ring-white"
          {...avatar}
        />
      ))}
      
      {showCount && remainingCount > 0 && (
        <div 
          className={`${config.container} rounded-full bg-gray-500 text-white flex items-center justify-center font-semibold ring-2 ring-white`}
        >
          <span className={config.text}>+{remainingCount}</span>
        </div>
      )}
    </div>
  )
}