import { useRef, useState } from 'react';

import { IconMoodPlus } from '@material-hu/icons/tabler';
import IconButton from '@material-hu/mui/IconButton';
import Stack from '@material-hu/mui/Stack';
import { useTheme } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

import Button from '@material-hu/components/design-system/Buttons/Button';
import IconSelector from '@material-hu/components/design-system/IconSelector';
import HuTooltip from '@material-hu/components/design-system/Tooltip';

import { useAuth } from 'src/contexts/JWTContext';
import { MAX_EMOJIS_LIMIT } from 'src/pages/dashboard/Conversations/constants';
import {
  type ConversationMessage,
  type SummaryReaction,
} from 'src/pages/dashboard/Conversations/types';
import { useLokaliseTranslation } from 'src/utils/i18n';

import ReactionTooltip from 'src/components/dashboard/reactions/ReactionTooltip';

import { useReactionsMutations } from '../../../hooks/useConversationsQueries';

import ReactionsList from './ReactionsList';

type MessageReactionsProps = {
  reactions: SummaryReaction[];
  message: ConversationMessage;
  showEmojiPicker: boolean;
  setShowEmojiPicker: (value: boolean) => void;
};

const MessageReactions = ({
  reactions,
  message,
  showEmojiPicker,
  setShowEmojiPicker,
}: MessageReactionsProps) => {
  const theme = useTheme();
  const [showReactionsList, setShowReactionsList] = useState(false);
  const { t } = useLokaliseTranslation(['chat', 'general']);
  const addReactionRef = useRef<HTMLDivElement>(null);
  const { mutate: mutateReaction } = useReactionsMutations();
  const { user } = useAuth();
  const userId = user?.id.toString() || '';
  const handleEmojiSelect = (emoji: string) => {
    const hasReacted = reactions
      .find(reaction => reaction.name === emoji)
      ?.users.some(reactionUser => reactionUser.id === Number(userId));

    mutateReaction({
      channel: message.channel,
      ts: message.hu_data.message_ts,
      name: emoji,
      hasReacted,
      userId,
    });
  };

  if (!reactions.length || message?.hidden) return null;

  return (
    <>
      <Stack
        sx={{
          flexDirection: 'row',
          alignItems: 'center',
          gap: 0.5,
        }}
      >
        {reactions.map(reaction => {
          const hasUserReacted = reaction.users.some(
            reactionUser => reactionUser.id === Number(userId),
          );

          return (
            <ReactionTooltip
              key={`${message.hu_data.message_ts}-${reaction.name}`}
              users={reaction.users.map(userReaction => userReaction.name)}
              reaction={{
                emoji: reaction.name,
                count: reaction.count,
                isLoggedUserReaction: hasUserReacted,
              }}
            >
              <IconButton
                onClick={() => handleEmojiSelect(reaction.name)}
                variant="tertiary"
                size="small"
                sx={{
                  minWidth: '47px',
                  border: '1.5px solid',
                  borderColor: hasUserReacted
                    ? theme.palette.new.action.button.background.primary.hover
                    : 'transparent',
                  backgroundColor: hasUserReacted
                    ? theme.palette.new.background.elements.brand
                    : theme.palette.new.background.layout.tertiary,
                  borderRadius: '6.78px',
                }}
              >
                <Typography variant="globalS">{reaction.name}</Typography>
                <Typography
                  variant="globalXS"
                  color={theme.palette.new.text.neutral.lighter}
                  fontWeight="fontWeightSemiBold"
                  sx={{
                    ml: 0.5,
                  }}
                >
                  {reaction.count}
                </Typography>
              </IconButton>
            </ReactionTooltip>
          );
        })}
        <HuTooltip
          disableTooltip={reactions?.length < MAX_EMOJIS_LIMIT}
          title={t('chat:messages.cannot_add_emoji')}
        >
          <Stack
            ref={addReactionRef}
            sx={{
              width: '32px',
              height: '32.5px',
              backgroundColor: theme.palette.new.background.layout.tertiary,
              borderRadius: '6.78px',
            }}
          >
            <IconSelector
              mode="emoji"
              icon={<IconMoodPlus size={14} />}
              onEmojiSelect={({ emoji }) => handleEmojiSelect(emoji)}
              open={showEmojiPicker}
              onOpenChange={setShowEmojiPicker}
              closeOnScroll
              slotProps={{
                iconButton: {
                  size: 'small',
                  variant: 'tertiary',
                  disabled: reactions?.length >= MAX_EMOJIS_LIMIT,
                },
              }}
            />
          </Stack>
        </HuTooltip>

        <Button
          variant="tertiary"
          size="small"
          onClick={() => {
            setShowReactionsList(true);
          }}
          sx={{
            minWidth: 'fit-content',
            p: 0,
          }}
        >
          {t('general:see_all')}
        </Button>
      </Stack>
      <ReactionsList
        anchorEl={showReactionsList ? addReactionRef.current : null}
        open={showReactionsList}
        onClose={() => {
          setShowReactionsList(false);
        }}
        channel={message.channel}
        ts={message.hu_data.message_ts}
        reactionsFromMessage={message.reactions}
      />
    </>
  );
};

export default MessageReactions;
