import { type FC, Fragment, useState } from 'react';

import { useModal } from '@material-hu/hooks/useModal';
import {
  IconDotsVertical,
  IconLogout,
  IconUserCheck,
} from '@material-hu/icons/tabler';
import Box from '@material-hu/mui/Box';
import IconButton from '@material-hu/mui/IconButton';
import Menu from '@material-hu/mui/Menu';
import MenuItem from '@material-hu/mui/MenuItem';
import Stack from '@material-hu/mui/Stack';
import { useTheme } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

import useHuSnackbar from '@material-hu/components/design-system/Snackbar';

import { useAuth } from 'src/contexts/JWTContext';
import {
  useGrantPermissionsAdmin,
  useRevokePermissionsAdmin,
} from 'src/pages/dashboard/Conversations/hooks/useConversationsQueries';
import { type Member } from 'src/pages/dashboard/Conversations/types';
import { compareIds } from 'src/pages/dashboard/Conversations/utils';
import { useLokaliseTranslation } from 'src/utils/i18n';

import LeaveGroup from './LeaveGroup';

type MembersActionsMenuProps = {
  userToModify: Member;
  isAdmin: boolean;
  channelId: string;
};

const MembersActionsMenu: FC<MembersActionsMenuProps> = props => {
  const { userToModify, isAdmin, channelId } = props;
  const { t } = useLokaliseTranslation(['chat', 'general']);
  const theme = useTheme();
  const { user } = useAuth();
  const { enqueueSnackbar, closeSnackbar: closePreviousSnackbar } =
    useHuSnackbar();
  const { mutateAsync: grantPermissions } = useGrantPermissionsAdmin();
  const { mutateAsync: revokePermissions } = useRevokePermissionsAdmin();

  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
  const open = Boolean(anchorEl);
  const handleCloseMenu = () => setAnchorEl(null);

  const handleOnClick = (event: React.MouseEvent<HTMLButtonElement>) =>
    setAnchorEl(event.currentTarget);

  const userName = `${userToModify.first_name} ${userToModify.last_name}`;

  const {
    modal: deleteMemberInfoModal,
    showModal: showDeleteMemberInfoModal,
    closeModal: closeDeleteMemberGroup,
  } = useModal(
    LeaveGroup,
    { fullWidth: true, maxWidth: 'sm' },
    {
      onClose: () => closeDeleteMemberGroup(),
      title: t('chat:groups.manage.delete_from_group_title', {
        user: userName,
      }),
      description: t('chat:groups.manage.delete_from_group_description'),
      channelId,
      primaryTextButton: t('general:delete'),
      secondaryTextButton: t('general:cancel'),
      userId: userToModify.id,
      userName,
      isLeaveGroup: false,
    },
  );

  const handleDeleteMember = () => {
    showDeleteMemberInfoModal();
    handleCloseMenu();
  };

  const handleGrantPermissions = async () => {
    closePreviousSnackbar();
    try {
      if (userToModify.is_admin) {
        await revokePermissions({
          channelId,
          user: userToModify.id.toString(),
        });
        enqueueSnackbar({
          title: t('chat:groups.manage.revoke_admin_success', {
            user: userName,
          }),
          variant: 'success',
        });
      } else {
        await grantPermissions({
          channelId,
          user: userToModify.id.toString(),
        });
        enqueueSnackbar({
          title: t('chat:groups.manage.assign_admin_success', {
            user: userName,
          }),
          variant: 'success',
        });
      }
    } catch (e) {
      enqueueSnackbar({
        title: t('chat:errors.grant_actions'),
        variant: 'error',
      });
    } finally {
      handleCloseMenu();
    }
  };

  const menuOptions = [
    {
      id: 'delete-member',
      enabled: true,
      option: (
        <MenuItem
          sx={{
            color: theme.palette.new.text.feedback.error,
          }}
          onClick={handleDeleteMember}
        >
          <Stack sx={{ flexDirection: 'row', gap: 1, alignItems: 'center' }}>
            <Stack
              sx={{
                backgroundColor: theme.palette.new.background.feedback.error,
                borderRadius: '50%',
                height: 40,
                width: 40,
                justifyContent: 'center',
                alignItems: 'center',
              }}
            >
              <IconLogout color={theme.palette.new.text.feedback.error} />
            </Stack>
            <Typography
              variant="globalS"
              fontWeight="fontWeightSemiBold"
            >
              {t('chat:groups.manage.delete_from_group')}
            </Typography>
          </Stack>
        </MenuItem>
      ),
    },

    {
      id: 'grant-permissions-member',
      enabled: true,
      option: (
        <MenuItem onClick={handleGrantPermissions}>
          <Stack sx={{ flexDirection: 'row', gap: 1, alignItems: 'center' }}>
            <Stack
              sx={{
                backgroundColor: theme.palette.new.background.layout.default,
                borderRadius: '50%',
                height: 40,
                width: 40,
                justifyContent: 'center',
                alignItems: 'center',
              }}
            >
              <IconUserCheck color={theme.palette.new.text.neutral.default} />
            </Stack>
            <Typography
              variant="globalS"
              fontWeight="fontWeightSemiBold"
            >
              {t(
                userToModify.is_admin
                  ? 'chat:groups.manage.remove_admin_modal'
                  : 'chat:groups.manage.assign_admin_modal',
              )}
            </Typography>
          </Stack>
        </MenuItem>
      ),
    },
  ];

  return (
    <Stack sx={{ flexDirection: 'row', alignItems: 'center' }}>
      {userToModify.is_admin && (
        <Typography
          sx={{ mr: 1 }}
          variant="globalXXS"
        >
          {t('chat:admin')}
        </Typography>
      )}
      {isAdmin && !compareIds(user?.id, userToModify.id) && (
        <IconButton
          size="small"
          id="admin-menu-button"
          aria-controls="admin-menu"
          aria-haspopup="true"
          onClick={handleOnClick}
        >
          <IconDotsVertical />
        </IconButton>
      )}
      <Menu
        id="admin-menu"
        elevation={2}
        anchorOrigin={{
          vertical: 'bottom',
          horizontal: 'right',
        }}
        transformOrigin={{
          vertical: 'top',
          horizontal: 'right',
        }}
        MenuListProps={{
          'aria-labelledby': 'admin-menu-button',
        }}
        anchorEl={anchorEl}
        open={open}
        onClose={handleCloseMenu}
      >
        <Box sx={{ width: 'fit-content' }}>
          {menuOptions.map(({ id, option }) => (
            <Fragment key={id}> {option} </Fragment>
          ))}
        </Box>
      </Menu>
      {deleteMemberInfoModal}
    </Stack>
  );
};

export default MembersActionsMenu;
