import { FC } from 'react';

import { useMutation } from 'react-query';
import { matchPath, useNavigate } from 'react-router-dom';

import { useModal } from '@material-hu/hooks/useModal';
import { IconTrash } from '@material-hu/icons/tabler';

import HuDialog from '@material-hu/components/design-system/Dialog';
import ListItem from '@material-hu/components/design-system/List/components/ListItem';
import MenuItem from '@material-hu/components/design-system/Menu/components/MenuItem';
import useHuSnackbar from '@material-hu/components/design-system/Snackbar';

import { logEvent } from 'src/config/logging';
import { useMoreMenu } from 'src/contexts/MoreMenuContext';
import useGeneralError from 'src/hooks/useGeneralError';
import { feedRoutes } from 'src/pages/dashboard/feed/routes';
import { deleteEventPostComment } from 'src/services/events';
import { deleteGroupPost, deleteGroupComment } from 'src/services/groups';
import { deletePost, deleteComment } from 'src/services/posts';
import { EventName } from 'src/types/amplitude';
import { getDeleteModalTexts } from 'src/utils/feed';
import { useLokaliseTranslation as useTranslation } from 'src/utils/i18n';

import { groupsRoutes } from '../../groups/routes';

type CommonDeleteProps = {
  id: number;
  onDelete: () => void;
  groupId?: number;
  eventId?: number;
  showIcon?: boolean;
  isLive?: boolean;
};

// Post-specific delete props
type PostOnlyDeleteProps = {
  isComment?: false;
  postId?: undefined;
};

// Comment-specific delete props
type CommentDeleteProps = {
  isComment: true;
  postId: number;
};

// Union type that allows either post or comment deletion props
type PostDeleteProps = CommonDeleteProps &
  (PostOnlyDeleteProps | CommentDeleteProps);

const PostDelete: FC<PostDeleteProps> = props => {
  const {
    id,
    isComment = false,
    postId,
    onDelete,
    groupId,
    eventId,
    showIcon = true,
    isLive = false,
  } = props;

  const { closeMenu } = useMoreMenu();
  const { t } = useTranslation(['web_only']);
  const { enqueueSnackbar } = useHuSnackbar();
  const showGeneralError = useGeneralError();
  const navigate = useNavigate();

  const handleDelete = () => deleteMutation.mutate();

  const openConfirm = () => showConfirmModal();
  const closeConfirm = () => {
    closeConfirmModal();
    closeMenu();
  };

  const deleteMutation = useMutation(
    () => {
      if (isComment && postId !== undefined) {
        if (eventId) {
          return deleteEventPostComment(eventId, postId, id);
        }
        if (groupId) {
          return deleteGroupComment(postId, groupId, id);
        }
        return deleteComment(id);
      }
      return groupId ? deleteGroupPost(id, groupId) : deletePost(id);
    },
    {
      onSuccess: () => {
        let eventName = EventName.POST_DELETE;
        if (groupId) {
          eventName = EventName.GROUPS_POST_DELETED;
        } else {
          eventName = EventName.FEED_POST_DELETED;
        }

        onDelete();
        enqueueSnackbar({
          title: t('post:delete_post_success'),
          variant: 'success',
        });
        logEvent(eventName, { postId: id, isComment, groupId, eventId });

        const isOnDetailPost = !!matchPath(
          groupId
            ? groupsRoutes.post.detail(groupId, id)
            : feedRoutes.post.detail(id),
          window.location.pathname,
        );
        if (isOnDetailPost)
          navigate(groupId ? groupsRoutes.detail(groupId) : feedRoutes.feed());
        closeMenu();
        closeConfirm();
      },
      onError: err => {
        if (isComment) {
          showGeneralError(err, t('comments.error_delete_comment'));
        } else {
          showGeneralError(err, t('post:error_delete_post'));
        }

        let eventName = EventName.POST_DELETE;
        if (groupId) {
          eventName = EventName.GROUPS_POST_DELETED;
        } else if (eventId) {
          eventName = EventName.EVENT_POST_DELETED;
        } else {
          eventName = EventName.FEED_POST_DELETED;
        }
        logEvent(eventName, { postId: id, isComment, groupId, eventId });
      },
    },
  );

  const {
    modal: confirmModal,
    showModal: showConfirmModal,
    closeModal: closeConfirmModal,
  } = useModal(
    HuDialog,
    {
      fullWidth: true,
      maxWidth: 'sm',
      sx: { zIndex: 2000 },
    },
    {
      onClose: closeMenu,
      ...getDeleteModalTexts({ isComment, isLive, t }),
      primaryButtonProps: {
        children: t('general:accept'),
        onClick: handleDelete,
        loading: deleteMutation.isLoading,
      },
      secondaryButtonProps: {
        children: t('general:cancel'),
        onClick: closeConfirm,
      },
    },
  );

  return (
    <>
      <MenuItem
        onClick={openConfirm}
        sx={{ p: 0 }}
      >
        <ListItem
          sx={{ p: 0 }}
          {...(showIcon ? { avatar: { Icon: IconTrash } } : {})}
          text={{ title: t('general:delete') }}
        />
      </MenuItem>
      {confirmModal}
    </>
  );
};

export default PostDelete;
