import { memo, useRef, useState } from 'react';

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

import HuMenu from '@material-hu/components/design-system/Menu';
import HuMenuItem from '@material-hu/components/design-system/Menu/components/MenuItem';

import {
  CONVERSATIONS_LIST_CONTAINER,
  CONVERSATIONS_MESSAGES_CONTAINER,
} from 'src/pages/dashboard/Conversations/constants';
import {
  type ConversationMessage,
  type Member,
  type SummaryReaction,
} from 'src/pages/dashboard/Conversations/types';

import { useDisableScroll } from '../../hooks/useDisableScroll';
import { useSettingMenu } from '../../hooks/useSettingMenu';

import MessageInfo from './MessageInfo';

type MessageSettingProps = {
  message: ConversationMessage;
  isLoggedUser: boolean;
  onReactClick: (anchorEl: HTMLElement | null) => void;
  reactions: SummaryReaction[];
  members: Member[];
  isContentClicked: boolean;
  isMessageForwarded?: boolean;
  isGroupConversation?: boolean;
  isPinnedMessage: boolean;
  pinnedMessagesCount: number;
};

const SELF_USER = 1;

const MessageSetting = ({
  message,
  isLoggedUser,
  onReactClick,
  reactions,
  members,
  isContentClicked,
  isMessageForwarded,
  isGroupConversation,
  isPinnedMessage,
  pinnedMessagesCount,
}: MessageSettingProps) => {
  const [isOpen, setIsOpen] = useState(false);
  const theme = useTheme();
  const buttonRef = useRef<HTMLButtonElement>(null);

  const { menuItems, openMenuMessageInfo, handleCloseMenuMessageInfo } =
    useSettingMenu({
      message,
      isLoggedUser,
      reactions,
      members,
      isMessageForwarded,
      isGroupConversation,
      isPinnedMessage,
      pinnedMessagesCount,
      onReactClick: () => onReactClick(buttonRef.current),
      onCloseMenu: () => setIsOpen(false),
    });

  const isDisabledScroll = isOpen || openMenuMessageInfo;

  useDisableScroll({
    isDisabled: isDisabledScroll,
    containerId: CONVERSATIONS_MESSAGES_CONTAINER,
    diabledPointerEvents: false,
  });

  useDisableScroll({
    isDisabled: isDisabledScroll,
    containerId: CONVERSATIONS_LIST_CONTAINER,
    diabledPointerEvents: false,
  });

  const bgMenu = isLoggedUser
    ? theme.palette.new.background.elements.brand
    : theme.palette.new.background.layout.tertiary;

  if (!menuItems.length) return;

  return (
    <Box
      className="message-setting"
      sx={{
        position: 'absolute',
        backgroundImage: `linear-gradient(to right, transparent 10%, ${bgMenu} 80%)`,
        zIndex: 50,
        height: '40px',
        width: '40px',
        top: 0,
        right: 0,
        borderBottomLeftRadius: '100%',
        paddingRight: '50px',
        opacity: 0,
        '&:hover': {
          opacity: 1,
        },
        ...(isOpen && {
          opacity: 1,
        }),
        visibility: isContentClicked ? 'hidden' : 'visible',
      }}
    >
      <IconButton
        ref={buttonRef}
        variant="tertiary"
        onClick={() => setIsOpen(true)}
        sx={{
          top: 2,
          right: 2,
          position: 'absolute',
          transform: isOpen ? 'rotate(180deg)' : 'rotate(0deg)',
          '&:hover': {
            backgroundColor: 'transparent',
          },
        }}
      >
        <IconChevronDown
          color={theme.palette.new.text.neutral.default}
          size={24}
        />
      </IconButton>
      <HuMenu
        open={isOpen}
        onClose={() => setIsOpen(false)}
        anchorEl={buttonRef.current}
        position="right"
        sx={{
          '& .MuiList-root': {
            display: 'flex',
            flexDirection: 'column',
            gap: 0.5,
            p: 0,
          },
          '& .MuiMenuItem-root:first-of-type, & .MuiMenuItem-root:last-of-type':
            {
              height: '51px',
            },
        }}
      >
        {menuItems.map(props => (
          <HuMenuItem
            {...props}
            key={props.id}
            sx={{
              minWidth: '236px',
              height: '40px',
              display: 'flex',
              justifyContent: 'space-between',
            }}
            onClick={props.onClick}
          >
            <Typography
              key="label"
              variant="globalXS"
              fontWeight="fontWeightSemiBold"
              color={
                props.id === 'delete'
                  ? theme.palette.new.action.button.background.error.default
                  : theme.palette.new.text.neutral.default
              }
            >
              {props.label}
            </Typography>
            <props.icon
              key="icon"
              size={24}
              style={{
                transform: props.id === 'replay' ? 'scaleX(-1)' : 'none',
              }}
              color={
                props.id === 'delete'
                  ? theme.palette.new.action.button.background.error.default
                  : theme.palette.new.text.neutral.default
              }
            />
          </HuMenuItem>
        ))}
      </HuMenu>
      <MessageInfo
        open={openMenuMessageInfo}
        channel={message.channel}
        messageTs={message.hu_data.message_ts}
        onClose={handleCloseMenuMessageInfo}
        totalMembers={members.length - SELF_USER}
      />
    </Box>
  );
};

export default memo(MessageSetting);
