import { IconBellRinging, type TablerIcon } from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';
import { alpha, useTheme } from '@material-hu/mui/styles';

import HuAvatar from '@material-hu/components/design-system/Avatar';

import { moduleIcons } from '../../constants';
import { type NotificationItem } from '../../types';
import { getNotificationOverlayProps } from '../utils';

type NotificationItemAvatarProps = {
  notification: NotificationItem;
  moduleIcon?: TablerIcon;
};

const NotificationItemAvatar = ({
  notification,
  moduleIcon,
}: NotificationItemAvatarProps) => {
  const theme = useTheme();
  const moduleValue = String(notification.module);
  const Icon =
    moduleIcon ??
    (moduleIcons[moduleValue as keyof typeof moduleIcons] as TablerIcon) ??
    IconBellRinging;

  const {
    overlaySrc,
    overlayText,
    overlayColor,
    isModule,
    hasOverlay: showOverlay,
  } = getNotificationOverlayProps(notification);

  const tertiaryFocus =
    theme.palette.new?.action?.button?.background?.tertiary?.focus;
  const reactionBg = tertiaryFocus
    ? alpha(tertiaryFocus, 0.8)
    : notification.iconBackgroundColor;

  return (
    <Stack sx={{ position: 'relative', display: 'inline-flex' }}>
      <HuAvatar
        src={notification.imageUrl || undefined}
        Icon={notification.imageUrl ? undefined : Icon}
        color="primary"
        size="medium"
        sx={{ width: 48, height: 48 }}
      />
      {showOverlay && (
        <HuAvatar
          src={overlaySrc}
          text={overlayText}
          color={overlayColor ?? 'default'}
          sx={{
            position: 'absolute',
            bottom: 0,
            right: 0,
            width: 24,
            height: 24,
            '& img': { width: 16, height: 16, objectFit: 'contain' },
            '& svg': { width: 16, height: 16 },
            '& .MuiTypography-root': { fontSize: 16, lineHeight: 1 },
            ...(isModule ? {} : { backgroundColor: reactionBg }),
          }}
        />
      )}
    </Stack>
  );
};

export default NotificationItemAvatar;
