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

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

import { Comment } from 'src/types/comments';
import { Article } from 'src/types/news';

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

export type ArticleCommentsProps = Pick<Article, 'id' | 'commentCount'> & {
  lastComments?: Comment[];
  commentsRef?: React.RefObject<HTMLElement>;
};

export const ArticleComments = ({
  id,
  commentCount,
  lastComments,
  commentsRef,
}: ArticleCommentsProps) => {
  const commentToScrollToRef = useRef(null);
  const [searchParams] = useSearchParams();
  const parentIdParams = searchParams.get('parentId');

  const { enqueueSnackbar } = useSnackbar();

  return (
    <CommentsSystem
      // Core props
      context="articles"
      postId={id}
      commentCount={commentCount}
      lastComments={lastComments || []}
      commentToScrollToRef={commentToScrollToRef}
      // Error handling
      onError={(error: Error) => {
        enqueueSnackbar({
          title: error.message || 'An error occurred',
          variant: 'error',
        });
      }}
      // Article-specific props
      ArticlesProps={{
        parentIdParams,
        commentsRef,
      }}
      containerSx={{ mt: 2 }}
    />
  );
};

export default ArticleComments;
