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

import { IconPin, IconPinned } 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 useFeed from 'src/hooks/queryHooks/feed';
import useGeneralError from 'src/hooks/useGeneralError';
import { feedKeys } from 'src/pages/dashboard/feed/queries';
import { pinPost, unpinPost } from 'src/services/posts';
import { useLokaliseTranslation as useTranslation } from 'src/utils/i18n';

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

export const PinPostMenuItem: FC<CopyUrlMenuItemProps> = props => {
  const { id, ...menuProps } = props;

  const showGeneralError = useGeneralError();
  const { t } = useTranslation(['post']);
  const queryClient = useQueryClient();
  const { pinnedPosts } = useFeed();

  const { data } = pinnedPosts();

  const pinPostsData =
    data?.pages?.flatMap(page => page?.data?.items || []) || [];

  const pinMutation = useMutation(() => pinPost(id), {
    onSuccess: () => {
      queryClient.invalidateQueries(feedKeys.pinned());
    },
    onError: err => {
      showGeneralError(err, t('post:error_pin_post'));
    },
  });

  const unpinMutation = useMutation(() => unpinPost(id), {
    onSuccess: () => {
      queryClient.invalidateQueries(feedKeys.pinned());
    },
    onError: err => {
      showGeneralError(err, t('post:error_unpin_post'));
    },
  });

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

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

  const handleClickUnpinPost = async () => {
    handleUnpinPost();
  };

  const isPinned = pinPostsData.some(post => post.id === id);

  if (isPinned) {
    return (
      <HuMenuItem
        onClick={handleClickUnpinPost}
        {...menuProps}
        sx={{ p: 0 }}
      >
        <HuListItem
          sx={{ p: 0 }}
          avatar={{ Icon: IconPin }}
          text={{ title: t('post:unpin') }}
        />
      </HuMenuItem>
    );
  }

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

export default PinPostMenuItem;
