import { useMemo } from 'react';
import { useInfiniteQuery } from 'react-query';
import { useOutletContext } from 'react-router-dom';

import SatisfactionDrawerCommentList from '@material-hu/components/composed-components/peopleExperience/surveyResults/SatisfactionDrawerCommentList';
import TableLoader from '@material-hu/components/design-system/Table/components/TableLoader';

import { pxKeys } from '../../../../../../../../../queries';
import { getQuestionAnswers } from '../../../../../../../../../services';
import {
  QuestionAnswersParams,
  QuestionTemplateType,
  type SegmentationFilterParams,
} from '../../../../../../../../../types';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { type ParsedQuestionStats } from '../../../types';

type QuestionCommentListProps = {
  questionId: number;
  surveyId: number;
  questionType: ParsedQuestionStats['type'];
  onScrollTop: () => void;
  stringAnswer?: string;
  integerAnswer?: number;
  renderDecorator?: (count: number) => React.ReactNode;
};

const QuestionCommentList = ({
  questionId,
  surveyId,
  questionType,
  stringAnswer,
  integerAnswer,
  onScrollTop,
  renderDecorator,
}: QuestionCommentListProps) => {
  const { t } = useLokaliseTranslation('people_experience');

  const { filters } = useOutletContext<{ filters: SegmentationFilterParams }>();

  const isTextQuestion = questionType === QuestionTemplateType.TEXT;

  const params: QuestionAnswersParams = {
    formId: surveyId,
    questionId,
    limit: 30,
    page: 1,
    isHighlighted: undefined,
    hasComment: isTextQuestion ? undefined : true,
    integerAnswer,
    stringAnswer,
    ...filters,
  };

  const {
    data: commentsData,
    isLoading: isLoadingComments,
    fetchNextPage: fetchNextCommentsPage,
    isFetchingNextPage: isFetchingNextCommentsPage,
  } = useInfiniteQuery({
    queryKey: pxKeys.infiniteQuestionAnswers(params),
    queryFn: ({ pageParam = 1 }) =>
      getQuestionAnswers({ ...params, page: pageParam }),
    getNextPageParam: lastPage => {
      if (lastPage.data.page === lastPage.data.totalPages) {
        return undefined;
      }
      return lastPage.data.page + 1;
    },
  });

  const commentsTableData = useMemo(() => {
    return (
      commentsData?.pages?.flatMap?.(page =>
        page.data.items.map(item => ({
          id: item.id,
          copetin: '',
          comment: isTextQuestion ? item.answer.string : item.comment,
        })),
      ) ?? []
    );
  }, [commentsData, isTextQuestion]);

  const totalCount = commentsData?.pages?.[0]?.data?.count ?? 0;

  return (
    <>
      <SatisfactionDrawerCommentList
        headerTitle={
          isTextQuestion ? t('answer.answers') : t('comment.comments')
        }
        comments={commentsTableData}
        loading={isLoadingComments}
        loadingMore={isFetchingNextCommentsPage}
        tableHeaderDecorator={
          !isLoadingComments ? renderDecorator?.(totalCount) : undefined
        }
      />
      {totalCount > 0 && commentsTableData.length > 0 && (
        <TableLoader
          loadedCount={commentsTableData.length}
          totalCount={totalCount}
          onLoadMore={fetchNextCommentsPage}
          onScrollToTop={onScrollTop}
        />
      )}
    </>
  );
};

export default QuestionCommentList;
