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

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

import useRequiredParams from 'src/hooks/useRequiredParams';
import { type GroupPost } from 'src/types/groups';

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

import { useGroupMember } from '../GroupMemberContext';

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

export const GroupPostComments = ({
  id,
  commentCount,
  lastComments,
  commentsEnabled = false,
  viewerCount,
  getViewers,
  viewersDisabled,
}: GroupPostCommentsProps) => {
  const commentToScrollToRef = useRef<HTMLElement | null>(null);
  const [searchParams] = useSearchParams();
  const parentIdParams = searchParams.get('parentId');
  const { id: groupId } = useRequiredParams(['id']);

  const { enqueueSnackbar } = useSnackbar();
  const { userIsMember, isGroupArchived, isGroupAdmin } = useGroupMember();

  return (
    <CommentsSystem
      // Core props
      context="groups"
      postId={id}
      commentCount={commentCount}
      lastComments={lastComments || []}
      commentToScrollToRef={commentToScrollToRef}
      commentsEnabled={commentsEnabled}
      viewerCount={viewerCount}
      getViewers={getViewers}
      viewersDisabled={viewersDisabled}
      // Error handling
      onError={(error: Error) => {
        enqueueSnackbar({
          title: error.message || 'An error occurred',
          variant: 'error',
        });
      }}
      // Group-specific props
      GroupsProps={{
        groupId,
        parentIdParams,
        userIsMember,
        isGroupArchived,
        isGroupAdmin,
      }}
    />
  );
};

export default GroupPostComments;
