import React from 'react'
import { sha256 } from 'js-sha256'

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

import { AddMissedButton, Avatar, Wrapper } 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,
  wrapperAS,
  width
}: {
  student: User
  present: boolean
  width?: string | number
  onAddUser?: (user: User) => void
  wrapperAS?: React.ElementType<any, keyof React.JSX.IntrinsicElements>;
}) => {
  return (
    <Wrapper warn={!present} as={wrapperAS} width={width}>
      <Avatar src={student.picture || getGravatarURL(student.email, null)} />
      <p style={{ marginTop: 6 }}>
        {student.name || student.preferred_username}{' '}
      </p>
      {onAddUser && !present && (
        <AddMissedButton onClick={() => onAddUser(student)}>
          add
        </AddMissedButton>
      )}
    </Wrapper>
  )
}

UserCard.defaultProps = {
  wrapperAS: 'div',
  onAddUser: void 0,
}
