import { type FC } from 'react';
import { useNavigate } from 'react-router-dom';

import { IconShare3 } from '@material-hu/icons/tabler';

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

import { feedRoutes } from 'src/pages/dashboard/feed/routes';
import { groupsRoutes } from 'src/pages/dashboard/groups/routes';
import { type GroupPost } from 'src/types/groups';
import { type Post } from 'src/types/posts';
import { useLokaliseTranslation as useTranslation } from 'src/utils/i18n';

type SharePostMenuItemProps = Omit<MenuItemProps, 'id' | 'onClick'> & {
  post: Post | GroupPost;
};

const resolveShareRoute = (post: Post | GroupPost): string => {
  if ('groupId' in post && typeof post.groupId === 'number') {
    return groupsRoutes.post.share(post.groupId, post.id);
  }
  const feedGroup = (post as Post).group;
  if (feedGroup?.id) {
    return groupsRoutes.post.share(feedGroup.id, post.id);
  }
  return feedRoutes.post.share(post.id);
};

export const SharePostMenuItem: FC<SharePostMenuItemProps> = ({
  post,
  ...menuProps
}) => {
  const { t } = useTranslation(['post']);
  const navigate = useNavigate();

  const handleClick = () => {
    navigate(resolveShareRoute(post));
  };

  return (
    <HuMenuItem
      onClick={handleClick}
      {...menuProps}
      sx={{ p: 0 }}
    >
      <HuListItem
        sx={{ p: 0 }}
        avatar={{ Icon: IconShare3 }}
        text={{ title: t('post:share_post') }}
      />
    </HuMenuItem>
  );
};

export default SharePostMenuItem;
