import { useInfiniteQuery } from 'react-query';
import { useNavigate } from 'react-router';

import Stack from '@material-hu/mui/Stack';

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

import useCustomServerTranslation from 'src/hooks/useCustomServerTranslation';
import useGeneralError from 'src/hooks/useGeneralError';
import useAttachCommonGroupListeners from 'src/pages/dashboard/groups/hooks/useAttachCommonGroupListeners';
import { groupsRoutes } from 'src/pages/dashboard/groups/routes';
import {
  addUserGroupFeedListDataReaction,
  profileKeys,
  removeUserGroupFeedListDataReaction,
} from 'src/pages/dashboard/profile/queries';
import { getGroupsPostsForUser } from 'src/services/groups';
import { FeedSource } from 'src/types/feed';
import { type UserProfile } from 'src/types/user';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { getNextCursor } from 'src/utils/pagination';

import InfiniteList from 'src/components/list/InfiniteList';
import PostCard from 'src/components/post/PostCard';

type GroupsTabProps = {
  user: UserProfile;
};

export const GroupsTab = ({ user: { id } }: GroupsTabProps) => {
  const { t } = useLokaliseTranslation(['profile', 'post']);
  const showGeneralError = useGeneralError();
  const navigate = useNavigate();

  useAttachCommonGroupListeners({
    enabled: true,
    source: FeedSource.PROFILE_GROUP_POSTS,
    profileUserId: id,
  });

  const { data, isLoading, fetchNextPage, hasNextPage, isFetchingNextPage } =
    useInfiniteQuery(
      profileKeys.groupFeed.list(id),
      ({ pageParam = '' }) => getGroupsPostsForUser(id, pageParam, 10),
      {
        getNextPageParam: getNextCursor,
        onError: err => showGeneralError(err, t('post:error_loading_posts')),
      },
    );

  const handleAddReaction = (postId: number, emoji: string, unified: string) =>
    addUserGroupFeedListDataReaction(id, postId, emoji, unified, true);

  const handleRemoveReaction = (postId: number, emoji: string) =>
    removeUserGroupFeedListDataReaction(id, postId, emoji, true);

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

  const groupsTitle = useCustomServerTranslation({
    module: 'GROUPS',
    defaultTranslationKey: 'groups',
    namespace: 'dashboard_sidebar_app',
  });

  if (data && !posts.length) {
    return (
      <StateCard
        title={t('empty_state.title.posts')}
        description={t('empty_state.description.posts')}
        primaryAction={{
          label: t('go_to_groups', { groups_miniapp_name: groupsTitle }),
          onClick: () => navigate(groupsRoutes.groups()),
        }}
      />
    );
  }

  return (
    <InfiniteList
      isSuccess={!!data}
      isLoading={isLoading}
      fetchNextPage={fetchNextPage}
      hasNextPage={hasNextPage}
      isFetchingNextPage={isFetchingNextPage}
    >
      {posts?.map(post => (
        <Stack
          key={post.id}
          sx={{ mb: 3 }}
        >
          <PostCard
            onAddReaction={handleAddReaction}
            onRemoveReaction={handleRemoveReaction}
            post={post}
          />
        </Stack>
      ))}
    </InfiniteList>
  );
};

export default GroupsTab;
