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

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

import useFeed from 'src/hooks/queryHooks/feed';
import {
  addFeedAndPinListDataReaction,
  removeFeedAndPinListDataReaction,
} from 'src/pages/dashboard/feed/queries';
import { feedRoutes } from 'src/pages/dashboard/feed/routes';

import PinnedPostsLayout from 'src/components/pinnedPosts/PinnedPostsLayout';
import PostCard from 'src/components/post/PostCard';

const PinnedPosts: FC = () => {
  const navigate = useNavigate();
  const { pinnedPosts } = useFeed();
  const {
    data: pinPostsData,
    isLoading,
    fetchNextPage,
    hasNextPage,
    isFetchingNextPage,
  } = pinnedPosts();

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

  const handleBack = () => {
    navigate(feedRoutes.feed());
  };

  const handleClose = () => {
    navigate(feedRoutes.feed());
  };

  return (
    <PinnedPostsLayout
      onBack={handleBack}
      onClose={handleClose}
      isLoading={isLoading}
      isEmpty={pinPosts.length === 0}
      hasNextPage={hasNextPage}
      isFetchingNextPage={isFetchingNextPage}
      fetchNextPage={fetchNextPage}
    >
      {pinPosts.map(post => (
        <Box
          key={post.id}
          sx={{ mt: 2 }}
          data-post-id={post.id}
        >
          <PostCard
            isPinned
            hidePinIcon
            onAddReaction={addFeedAndPinListDataReaction}
            onRemoveReaction={removeFeedAndPinListDataReaction}
            post={post}
          />
        </Box>
      ))}
    </PinnedPostsLayout>
  );
};

export default PinnedPosts;
