import { useInfiniteQuery } from 'react-query';

import * as colors from '@material-hu/mui/colors';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import { getFavDimensionStats } from '../services';
import {
  FavDimensionStatsParams,
  FavDimensionStatsResponse,
  Topic,
} from '../types';
import { LokaliseTFunction, useLokaliseTranslation } from 'src/utils/i18n';

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

import CellMessage from './CellMessage';
import FavBaseTableList from './FavBaseTableList';
import FavDescriptionTitle from './FavDescriptionTitle';
import FavorabilityChart from './FavorabilityChart';

const renderDescriptionColumn = ({
  row,
  t,
}: {
  row: FavDimensionStatsResponse;
  t: LokaliseTFunction;
}) => {
  return (
    <Stack>
      <Typography variant="subtitle2">{row.title}</Typography>
      <Typography
        variant="body2"
        sx={theme => ({ color: theme.palette.new.text.neutral.lighter })}
      >
        {getFavorabilityCountText({
          t,
          translationKey: 'question.question',
          hasPassedThreshold: row.passedThreshold,
          count: row.questionsCount,
        })}
      </Typography>
    </Stack>
  );
};

const renderDistributionColumn = ({
  row,
  t,
}: {
  row: FavDimensionStatsResponse;
  t: LokaliseTFunction;
}) => {
  if (!row.passedThreshold) {
    return <CellMessage title={t('NOT_ENOUGH_ANSWERS')} />;
  }

  const { metadata } = row;
  return (
    <FavorabilityChart
      positives={metadata?.promoters ?? 0}
      neutrals={metadata?.neutrals ?? 0}
      negatives={metadata?.detractors ?? 0}
    />
  );
};

type FavDimensionListProps = {
  surveyId: number;
  onSelectDimension: (dimension: Topic) => void;
};

const FavDimensionList = ({
  surveyId,
  onSelectDimension,
}: FavDimensionListProps) => {
  const { t } = useLokaliseTranslation('people_experience');

  const requestParams: FavDimensionStatsParams = {
    surveyId,
  };

  const { data, isLoading, isPreviousData, hasNextPage, fetchNextPage } =
    useInfiniteQuery(
      pxKeys.favDimensionStats(requestParams),
      ({ pageParam = 0 }) => {
        return getFavDimensionStats({
          limit: 30,
          page: pageParam,
          ...requestParams,
        });
      },
      {
        keepPreviousData: true,
        getNextPageParam: lastPage => {
          if (lastPage.page === lastPage.totalPages) {
            return undefined;
          }

          return lastPage.page;
        },
      },
    );

  const tableData = data?.pages.flatMap(page => page.items) ?? [];
  const count = data?.pages[0].count;

  return (
    <FavBaseTableList
      data={tableData}
      isLoading={isLoading}
      hasNextPage={hasNextPage}
      onLoadMore={fetchNextPage}
      isPreviousData={isPreviousData}
      descriptionColumnTitle={
        <FavDescriptionTitle
          title={t('dimension_one')}
          description={t('DIMENSION_QUANTITY')}
          count={count}
        />
      }
      renderDescriptionColumn={row => renderDescriptionColumn({ row, t })}
      renderDistributionColumn={row => renderDistributionColumn({ row, t })}
      slotProps={{
        dataRow: row => ({
          onClick: () => onSelectDimension(row),
        }),
        distributionColumn: row => ({
          sx: {
            bgcolor: theme =>
              row.passedThreshold
                ? undefined
                : theme.palette.new.background.layout.default,
          },
        }),
      }}
    />
  );
};

export default FavDimensionList;
