import React from 'react'
import { sha256 } from 'js-sha256'
import { useState } from 'react'
import { Box, useColorMode } from '@chakra-ui/react'
import { CheckCircleIcon, AddIcon } from '@chakra-ui/icons'

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

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

export function getGravatarURL(email, user) {
  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,
  onAddUser = undefined,
  wrapperAS = 'div',
  width,
  recentlyPresent = false
}: {
  student: User
  present: boolean
  width?: string | number
  onAddUser?: (user: User) => void
  wrapperAS?: React.ElementType<any, keyof React.JSX.IntrinsicElements>;
  recentlyPresent?: boolean
}) => {
  const { colorMode } = useColorMode();
  const [imageError, setImageError] = useState(false);
  
  return (
    <Wrapper 
      warn={!present} 
      as={wrapperAS} 
      width={width}
      className={!present ? 'warn' : recentlyPresent ? 'recent' : ''}
    >
      <Avatar 
        src={imageError ? getGravatarURL(student.email, null) : (student.picture || getGravatarURL(student.email, null))} 
        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>
      {onAddUser && !present && (
        <AddMissedButton onClick={() => onAddUser(student)} aria-label="Отметить присутствие">
          <AddIcon boxSize={3} />
        </AddMissedButton>
      )}
    </Wrapper>
  )
}
