import React, { FC, useMemo } from 'react'
import { Avatar, AvatarBadge, Box, Flex, Heading, Icon, Text } from '@chakra-ui/react'
import { formatRelative } from 'date-fns'
import itLocale from 'date-fns/locale/it'
import { AiOutlineMail } from 'react-icons/ai'

export type NotificationItemProps = {
  id: string
  title: string
  body?: string
  icon?: string
  senderIcon?: string
  senderName?: string
  createdAt: string
  isUnread?: boolean
  clickUrl?: string
  onClick?: (id: string, clickUrl?: string) => void
}

export const NotificationItem: FC<NotificationItemProps> = ({
  title,
  body,
  icon,
  senderIcon,
  senderName,
  id,
  createdAt,
  isUnread,
  clickUrl,
  onClick,
}) => {
  const formattedCreatedAt = useMemo(() => {
    return formatRelative(new Date(createdAt), new Date(), { locale: itLocale })
  }, [createdAt])

  const bgColor = useMemo(() => {
    return isUnread ? 'gray.100' : 'white'
  }, [isUnread])

  const handleClick = useMemo(() => {
    return () => {
      onClick?.(id, clickUrl)
    }
  }, [clickUrl, id, onClick])

  return (
    <Flex
      role="button"
      tabIndex={0}
      alignItems="flex-start"
      borderTop="1px solid"
      borderTopColor="gray.200"
      p={3}
      onClick={handleClick}
      bgColor={bgColor}
      _hover={{
        bg: 'gray.50',
      }}
    >
      <Box pt={2}>
        {icon && (senderIcon || senderName) ? (
          <Avatar src={senderIcon} name={senderName}>
            <AvatarBadge
              boxSize="1.25em"
              bgImage={`url(${icon})`}
              bgPos="center"
              bgRepeat="no-repeat"
              bgSize="contain"
            />
          </Avatar>
        ) : icon ? (
          <Avatar src={icon} name={title} />
        ) : senderIcon || senderName ? (
          <Avatar src={senderIcon} name={senderName} />
        ) : (
          <Avatar icon={<Icon as={AiOutlineMail} />} />
        )}
      </Box>
      <Flex flexDir="column" alignItems="flex-start" pl={3}>
        {title && body && (
          <Heading as="h3" size="xs" color="gray.800">
            {title}
          </Heading>
        )}
        <Text fontSize="sm" my={2}>
          {!body ? title : body}
        </Text>

        <Text fontSize="xs" color="blackAlpha.600" as="span">
          {formattedCreatedAt}
        </Text>
      </Flex>
    </Flex>
  )
}
