import { useRef } from 'react';
import { useSearchParams } from 'react-router-dom';

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

import { useAuth } from 'src/contexts/JWTContext';
import { type Post } from 'src/types/posts';

import { CommentsSystem } from 'src/components/comments/CommentsSystem';
import { useSegmentationDrawer } from 'src/components/segmentations/useSegmentationDrawer';

const EMPTY_SEGMENTATION_MAP = new Map();

export type PostCommentsProps = Pick<
  Post,
  | 'id'
  | 'commentCount'
  | 'lastComments'
  | 'user'
  | 'segmentation'
  | 'hasBeenSegmented'
  | 'commentsEnabled'
> & {
  viewerCount?: number;
  getViewers?: (params?: {
    page?: number;
    limit?: number;
    search?: string;
  }) => Promise<any>;
  viewersDisabled?: boolean;
};

export const PostComments = ({
  id,
  commentCount,
  lastComments,
  user,
  segmentation,
  hasBeenSegmented,
  commentsEnabled = true,
  viewerCount,
  getViewers,
  viewersDisabled,
}: PostCommentsProps) => {
  const commentToScrollToRef = useRef(null);
  const [searchParams] = useSearchParams();
  const parentIdParams = searchParams.get('parentId');

  const { enqueueSnackbar } = useSnackbar();
  const { user: loggedUser } = useAuth();

  const isLoggedUserPost = loggedUser?.id === user.id;

  const { drawer: segmentationDrawer, showDrawer: showSegmentationDrawer } =
    useSegmentationDrawer({
      selectedItems: EMPTY_SEGMENTATION_MAP,
      readOnly: true,
    });

  return (
    <CommentsSystem
      context="feed"
      postId={id}
      commentCount={commentCount}
      lastComments={lastComments || []}
      commentToScrollToRef={commentToScrollToRef}
      commentsEnabled={commentsEnabled}
      viewerCount={viewerCount}
      getViewers={getViewers}
      viewersDisabled={viewersDisabled}
      onError={(error: Error) => {
        enqueueSnackbar({
          title: error.message,
          variant: 'error',
        });
      }}
      FeedProps={{
        parentIdParams,
        showSegmentation: isLoggedUserPost,
        segmentation,
        hasBeenSegmented,
        onOpenSegmentationDrawer: () => showSegmentationDrawer({}),
        segmentationDrawer,
      }}
    />
  );
};

export default PostComments;
