import { useQuery } from 'react-query';
import { useParams } from 'react-router-dom';

import { concat } from 'lodash-es';
import { useServerPagination } from '@material-hu/hooks/useServerPagination';
import Box from '@material-hu/mui/Box';
import CircularProgress from '@material-hu/mui/CircularProgress';
import ListItem from '@material-hu/mui/ListItem';
import ListItemText from '@material-hu/mui/ListItemText';
import Paper from '@material-hu/mui/Paper';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import { PeopleExperience } from '@material-hu/components/composed-components/peopleExperience';

import { getQuestionAnswers } from '../services';
import {
  type CommentsFilter,
  type QuestionAnswersParams,
  type QuestionTemplate,
  QuestionTemplateType,
} from '../types';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { pxKeys } from '../queries';
import { getPercent } from '../utils';

import EmptyState from './EmptyState';

const { ListWithDivider } = PeopleExperience;

type CommentsListProps = {
  filter?: CommentsFilter | null;
  questionId: QuestionTemplate['id'];
  questionFormat: QuestionTemplate['type'];
  totalComments: number;
};

const CommentsList = ({
  filter,
  questionId,
  questionFormat,
  totalComments,
}: CommentsListProps) => {
  const urlParams = useParams();
  const surveyId = Number(urlParams.id);
  const { t } = useLokaliseTranslation('people_experience');
  const { paginationController, pagination } = useServerPagination({
    labelRowsPerPage: t('ROWS_PER_PAGE'),
  });

  const params: QuestionAnswersParams = {
    formId: surveyId,
    questionId,
    isHighlighted: undefined,
    hasComment: questionFormat === QuestionTemplateType.TEXT ? undefined : true,
    page: pagination.page + 1,
    limit: pagination.limit,
    ...filter?.value,
  };

  const { data, isLoading } = useQuery(
    pxKeys.questionAnswers(params),
    () => getQuestionAnswers(params),
    { select: res => res.data, enabled: !!questionId },
  );

  const hasDisplayData = !!data?.count && data?.passedThreshold;

  return (
    <Paper>
      <Stack
        sx={{
          flexDirection: 'row',
          bgcolor: theme => theme.palette.new.background.layout.default,
          p: 2,
          gap: 1,
          borderTopLeftRadius: 'inherit',
          borderTopRightRadius: 'inherit',
          alignItems: 'center',
        }}
      >
        <Typography
          variant="overline"
          display="block"
          sx={{ flex: 1 }}
        >
          {t('comment.comments')}
        </Typography>
      </Stack>
      {filter && (
        <Stack
          sx={theme => ({
            bgcolor:
              filter.foreColor ??
              theme.palette.new.action.background.brand.default,
            p: 2,
            color: filter.textColor ?? theme.palette.new.text.neutral.brand,
          })}
        >
          <Typography variant="subtitle2">
            &quot;
            {filter.label}
            &quot;
          </Typography>
          {!!data?.count && (
            <Typography variant="caption">
              {`${t('percent_selected', { count: getPercent(data.count, totalComments) })} - ${t(
                'COMMENTS_COUNT',
                {
                  count: data.count,
                },
              )}`}
            </Typography>
          )}
        </Stack>
      )}
      {isLoading && (
        <Stack sx={{ alignItems: 'center', p: 4 }}>
          <CircularProgress />
        </Stack>
      )}
      {!hasDisplayData && !isLoading && (
        <EmptyState
          title={t('NOT_ENOUGH_DATA_TITLE')}
          description={t('NOT_ENOUGH_DATA_DESCRIPTION')}
          slotProps={{
            root: {
              sx: {
                p: 2,
              },
            },
          }}
        />
      )}
      {data?.count !== 0 && (
        <ListWithDivider
          dividerProps={{ variant: 'fullWidth' }}
          sx={{ pb: 0 }}
          items={concat(
            data?.items?.map(({ id, comment, answer }) => (
              <ListItem
                key={id}
                sx={{ gap: 2 }}
              >
                <ListItemText>{`“${questionFormat === QuestionTemplateType.TEXT ? answer.string : comment}”`}</ListItemText>
              </ListItem>
            )),
            <Box sx={{ py: 1 }}>{paginationController(data?.count ?? 0)}</Box>,
          )}
        />
      )}
    </Paper>
  );
};

export default CommentsList;
