import { type FC } from 'react';
import { useMutation } from 'react-query';

import { IconPin, IconPinned } from '@material-hu/icons/tabler';
import MenuItem from '@material-hu/mui/MenuItem';

import HuListItem from '@material-hu/components/design-system/List/components/ListItem';
import { type MenuItemProps } from '@material-hu/components/design-system/Menu/components/MenuItem/types';

import useGeneralError from 'src/hooks/useGeneralError';
import useRequiredParams from 'src/hooks/useRequiredParams';
import { pinGroupPost, unpinGroupPost } from 'src/services/groups';
import { useLokaliseTranslation as useTranslation } from 'src/utils/i18n';

import { invalidatePinAndPostList } from '../queries';

type CopyUrlMenuItemProps = Omit<MenuItemProps, 'id'> & {
  id: number;
  isPinned?: boolean;
};

const GroupPinPostMenuItem: FC<CopyUrlMenuItemProps> = props => {
  const { id: postId, isPinned = false, ...menuProps } = props;

  const { id: groupId } = useRequiredParams(['id']);

  const showGeneralError = useGeneralError();
  const { t } = useTranslation(['group']);

  const pinMutation = useMutation(() => pinGroupPost(groupId, postId), {
    onSuccess: () => {
      invalidatePinAndPostList(Number(groupId));
    },
    onError: err => {
      showGeneralError(err, t('post:error_pin_post'));
    },
  });

  const unpinMutation = useMutation(() => unpinGroupPost(groupId, postId), {
    onSuccess: () => {
      invalidatePinAndPostList(Number(groupId));
    },
    onError: err => {
      showGeneralError(err, t('post:error_unpin_post'));
    },
  });

  const handlePinPost = () => pinMutation.mutate();

  const handleUnpinPost = () => unpinMutation.mutate();

  return (
    <>
      {isPinned && (
        <MenuItem
          onClick={handleUnpinPost}
          {...menuProps}
          sx={{ p: 0 }}
        >
          <HuListItem
            sx={{ p: 0 }}
            avatar={{ Icon: IconPin }}
            text={{ title: t('post:unpin') }}
          />
        </MenuItem>
      )}
      {!isPinned && (
        <MenuItem
          onClick={handlePinPost}
          {...menuProps}
          sx={{ p: 0 }}
        >
          <HuListItem
            sx={{ p: 0 }}
            avatar={{ Icon: IconPinned }}
            text={{ title: t('post:pin') }}
          />
        </MenuItem>
      )}
    </>
  );
};

export default GroupPinPostMenuItem;
