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

import { isNil } from 'lodash-es';

import SatisfactionStatsHeader from '@material-hu/components/composed-components/peopleExperience/surveyResults/SatisfactionStatsHeader';
import SatisfactionStatsHeaderSkeleton from '@material-hu/components/composed-components/peopleExperience/surveyResults/SatisfactionStatsHeaderSkeleton';

import { pxKeys } from '../../../../../queries';
import { distributeRoundedPercentages } from '../../../../../utils/formatting';
import { getFavListIndexStats } from '../../../../../services';
import {
  type ManagerSurvey,
  type SegmentationFilterParams,
} from '../../../../../types';
import { useLokaliseTranslation } from 'src/utils/i18n';

import ScoreDifferenceDescription from '../../ScoreDifferenceDescription';
import useNpsChartTooltip from '../hooks/useNpsChartTooltip';
import { getCountDescription } from '../utils';

type GeneralSatisfactionHeaderProps = {
  surveyId: ManagerSurvey['id'];
};

const GeneralSatisfactionHeader = ({
  surveyId,
}: GeneralSatisfactionHeaderProps) => {
  const { t } = useLokaliseTranslation('people_experience');
  const { filters } = useOutletContext<{ filters: SegmentationFilterParams }>();

  const queryParams = {
    surveyId,
    ...filters,
  };

  const { data, isLoading, isPreviousData } = useQuery(
    pxKeys.favListIndexStats(queryParams),
    () => getFavListIndexStats(queryParams),
    {
      select: response => response.data,
      keepPreviousData: true,
    },
  );

  const { getTooltipTitle } = useNpsChartTooltip();

  if (isLoading || isNil(data)) {
    return <SatisfactionStatsHeaderSkeleton />;
  }

  const [promoters, detractors, neutrals] = distributeRoundedPercentages([
    data.stats?.promoters ?? 0,
    data.stats?.detractors ?? 0,
    data.stats?.neutrals ?? 0,
  ]);

  return (
    <SatisfactionStatsHeader
      title={t('satisfaction.general')}
      score={data.score}
      scoreLabel={t('score')}
      differenceIndicatorMeta={{
        scoreLabel: t('filter.title'),
        baseScoreLabel: t('survey.survey'),
        footerLabel: t('comparing_results'),
        baseScore: data.baseScore,
        scoreDifference: data.baseScoreDifference,
        getScoreDifferenceDescription: () =>
          !!data.baseScoreDifference && (
            <ScoreDifferenceDescription difference={data.baseScoreDifference} />
          ),
      }}
      chartMeta={{
        title: t('answer.distribution'),
        description: [
          getCountDescription(
            'answer.answer_custom_count',
            data.answersAmount,
            t,
          ),
          getCountDescription(
            'participant.participant_custom_count',
            data.respondentsAmount,
            t,
          ),
          getCountDescription(
            'comment.comment_custom_count',
            data.commentsAmount,
            t,
          ),
        ].join(' | '),
        promoters,
        detractors,
        neutrals,
        getTooltipTitle,
      }}
      slotProps={{
        root: {
          sx: {
            ...(isPreviousData && { opacity: 0.5, pointerEvents: 'none' }),
          },
        },
      }}
    />
  );
};

export default GeneralSatisfactionHeader;
