import { useMemo, useState } from 'react';

import { useInfiniteQuery } from 'react-query';

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

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

import useHuGoTheme from 'src/hooks/useHuGoTheme';
import { Comment as CommentType } from 'src/types/comments';
import { getCurrentCommentsCount } from 'src/utils/comments';
import { orderByDate } from 'src/utils/date';
import { useLokaliseTranslation as useTranslation } from 'src/utils/i18n';

import { Comment, CommentProps } from 'src/components/comments/Comment';
import { GetChildCommentsQueryConfigReturn } from 'src/components/comments/commentConfigs';

export type ChildCommentListProps = Omit<CommentProps, 'comment'> & {
  commentChildren?: CommentType[];
  childrenNumber?: number;
  queryConfig: GetChildCommentsQueryConfigReturn;
};

const ChildCommentList = ({
  postId,
  context,
  commentChildren = [],
  childrenNumber = 0,
  onDelete,
  onEdit,
  onReply,
  onRemoveReaction,
  onAddReaction,
  maxAttachmentsBytes,
  queryConfig,
  canManageComments,
  canReact,
  isGroupArchived,
  userIsMember,
  isGroupAdmin,
}: ChildCommentListProps) => {
  const [openChildComments, setOpenChildComments] = useState(false);
  const HugoThemeProvider = useHuGoTheme();

  const { t } = useTranslation('web_only');

  const { data, hasNextPage, isFetchingNextPage, isFetching, fetchNextPage } =
    useInfiniteQuery(queryConfig.queryKey, queryConfig.queryFn, {
      getNextPageParam: queryConfig.getNextPageParam,
      enabled: openChildComments,
      ...(queryConfig.select && { select: queryConfig.select }),
    });

  const childCommentsLength = getCurrentCommentsCount(data);

  const showLoadMoreAnswers = useMemo(
    () =>
      openChildComments
        ? hasNextPage && childrenNumber > childCommentsLength
        : childrenNumber > (commentChildren?.length ?? 0),
    [
      openChildComments,
      hasNextPage,
      childrenNumber,
      childCommentsLength,
      commentChildren,
    ],
  );

  const handleLoadMoreAnswers = () =>
    openChildComments ? fetchNextPage() : setOpenChildComments(true);

  const isLoadingChilds = (isFetching && !data?.pages) || isFetchingNextPage;
  const commentsToRender = openChildComments
    ? (data?.pages?.flatMap(page =>
        'items' in page.data ? page.data.items : page.data,
      ) ?? [])
    : commentChildren;

  return (
    <HugoThemeProvider>
      {showLoadMoreAnswers && !isLoadingChilds && (
        <Button
          variant="tertiary"
          sx={{
            width: 'fit-content',
            ml: 5,
            mb: 1.5,
          }}
          onClick={handleLoadMoreAnswers}
        >
          <Typography
            variant="globalXS"
            fontWeight="fontWeightSemiBold"
            sx={{ color: theme => theme.palette.new.text.neutral.default }}
          >
            {t('comments.show_more_answers')}
          </Typography>
        </Button>
      )}
      {openChildComments && isLoadingChilds && (
        <Stack sx={{ alignItems: 'center', my: 1 }}>
          <CircularProgress />
        </Stack>
      )}
      {commentsToRender?.sort(orderByDate)?.map(childComment => (
        <Stack
          sx={{ ml: 6 }}
          key={childComment.id}
        >
          <Comment
            postId={postId}
            context={context}
            comment={childComment}
            onDelete={onDelete}
            onEdit={onEdit}
            onReply={onReply}
            onAddReaction={onAddReaction}
            onRemoveReaction={onRemoveReaction}
            maxAttachmentsBytes={maxAttachmentsBytes}
            canManageComments={canManageComments}
            canReact={canReact}
            isGroupArchived={isGroupArchived}
            userIsMember={userIsMember}
            isGroupAdmin={isGroupAdmin}
          />
        </Stack>
      ))}
    </HugoThemeProvider>
  );
};

export default ChildCommentList;
