import React, { useMemo } from 'react'
import { sha256 } from 'js-sha256'
import { useState, useEffect, useRef } from 'react'
import { Box, useColorMode, Text } from '@chakra-ui/react'
import { CheckCircleIcon, AddIcon } from '@chakra-ui/icons'
import { motion, AnimatePresence } from 'framer-motion'
import { useTranslation } from 'react-i18next'

import { Reaction, User } from '../../__data__/model'

import { Avatar, Wrapper, NameOverlay } from './style'

// Map of reaction types to emojis
const REACTION_EMOJIS = {
  thumbs_up: '👍',
  heart: '❤️',
  laugh: '😂',
  wow: '😮',
  clap: '👏'
}

export function getGravatarURL(email) {
  if (!email) return void 0
  const address = String(email).trim().toLowerCase()
  const hash = sha256(address)

  return `https://www.gravatar.com/avatar/${hash}?d=robohash`
}

export const UserCard = ({
  student,
  present,
  wrapperAS = 'div',
  width,
  recentlyPresent = false,
  reaction
}: {
  student: User
  present: boolean
  width?: string | number
  wrapperAS?: React.ElementType<any, keyof React.JSX.IntrinsicElements>
  recentlyPresent?: boolean
  reaction?: Reaction
}) => {
  const { colorMode } = useColorMode();
  const { t } = useTranslation();
  const [imageError, setImageError] = useState(false);
  const [showReaction, setShowReaction] = useState(false);
  const timeoutRef = useRef<NodeJS.Timeout | null>(null);

  const randomGravatarPath = useMemo(() => Math.random() * 1000, [])
  
  // Обрабатываем изменение реакции
  useEffect(() => {
    if (reaction) {
      setShowReaction(true);
      
      // Очищаем предыдущий таймер если он есть
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
      }
      
      // Устанавливаем новый таймер
      timeoutRef.current = setTimeout(() => {
        setShowReaction(false);
        timeoutRef.current = null;
      }, 3000);
    }
    
    return () => {
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
      }
    };
  }, [reaction]);
  
  return (
    <Wrapper 
      warn={!present} 
      as={wrapperAS} 
      width={width}
      className={!present ? 'warn' : recentlyPresent ? 'recent' : ''}
      position="relative"
    >
      <Avatar 
        src={imageError ? getGravatarURL(student.email || randomGravatarPath) : (student.picture || getGravatarURL(student.email))} 
        onError={() => {
          if (!imageError && student.picture) {
            setImageError(true);
          }
        }} 
      />
      <NameOverlay>
        {student.name || student.preferred_username}
        {present && (
          <Box as="span" ml={2} display="inline-block" color={recentlyPresent ? "green.100" : "green.300"}>
            <CheckCircleIcon boxSize={3} />
          </Box>
        )}
      </NameOverlay>
      
      {/* Анимация реакции */}
      <AnimatePresence>
        {showReaction && reaction && (
          <motion.div
            key={reaction._id}
            initial={{ opacity: 0, scale: 0.5, y: 0 }}
            animate={{ opacity: 1, scale: 1, y: 0 }}
            exit={{ opacity: 0, scale: 0.5, y: -20 }}
            transition={{ duration: 0.5 }}
            style={{
              position: 'absolute',
              top: '10px',
              right: '10px',
              zIndex: 10,
              pointerEvents: 'none',
              display: 'flex',
              justifyContent: 'center',
              alignItems: 'center',
              background: colorMode === 'light' ? 'rgba(255, 255, 255, 0.8)' : 'rgba(0, 0, 0, 0.6)',
              borderRadius: '50%',
              padding: '2px',
              boxShadow: '0 2px 5px rgba(0,0,0,0.2)'
            }}
            title={t(`journal.pl.reactions.${reaction.reaction}`)}
          >
            <Text 
              fontSize="3xl"
              sx={{
                filter: 'drop-shadow(0 1px 2px rgba(0,0,0,0.3))',
                transform: 'scale(1.2)',
                display: 'flex'
              }}
            >
              {REACTION_EMOJIS[reaction.reaction] || reaction.reaction}
            </Text>
          </motion.div>
        )}
      </AnimatePresence>
    </Wrapper>
  )
}
