import { useMemo } from 'react';

import { Emoji } from 'emoji-picker-react';
import IconButton, { IconButtonProps } from '@material-hu/mui/IconButton';
import { useTheme } from '@material-hu/mui/index';
import Typography from '@material-hu/mui/Typography';

import { Reaction as ReactionType } from 'src/types/reaction';
import { useLokaliseTranslation as useTranslation } from 'src/utils/i18n';

import { REACTION_BUTTON_HEIGHT } from '.';

export type ReactionProps = IconButtonProps & {
  reaction: ReactionType;
  onAdd: (emoji: string, unified: string) => void;
  onRemove: (emoji: string) => void;
};

const Reaction = ({
  reaction,
  onAdd,
  onRemove,
  ...iconButtonProps
}: ReactionProps) => {
  const { emoji, unified, count, isLoggedUserReaction } = reaction;
  const { t } = useTranslation('web_only');
  const theme = useTheme();

  const handleClick = () => {
    if (emoji && unified) {
      isLoggedUserReaction ? onRemove(emoji) : onAdd(emoji, unified);
    }
  };

  const getLabel = () =>
    isLoggedUserReaction
      ? t('reactions.reaction_remove', { emoji })
      : t('reactions.reaction_add', { emoji });

  const dinamicStyles = useMemo(() => {
    return {
      backgroundColor: isLoggedUserReaction
        ? theme.palette.new.background.layout.brand
        : theme.palette.new.background.elements.grey,
      outline: '1.5px solid',
      outlineColor: isLoggedUserReaction
        ? theme.palette.new.action.button.background.primary.hover
        : 'transparent',
      outlineOffset: '-1.5px',
    };
  }, [theme, isLoggedUserReaction]);

  return (
    <IconButton
      sx={{
        gap: 0.5,
        py: 0.75,
        px: 1,
        height: REACTION_BUTTON_HEIGHT,
        ...dinamicStyles,
      }}
      aria-label={getLabel()}
      aria-pressed={isLoggedUserReaction}
      onClick={handleClick}
      size="large"
      {...iconButtonProps}
    >
      {unified && (
        <Emoji
          unified={unified}
          size={16}
        />
      )}
      {!unified && <>{emoji}</>}
      <Typography
        variant="globalXS"
        fontWeight="fontWeightSemiBold"
        component="span"
      >
        {count}
      </Typography>
    </IconButton>
  );
};

export default Reaction;
