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,
  formatAmount,
} from '../../../../../utils/formatting';
import { getFavDimensionIndexStats } from '../../../../../services';
import {
  type ManagerSurvey,
  type SegmentationFilterParams,
  type Topic,
} from '../../../../../types';
import { useLokaliseTranslation } from 'src/utils/i18n';

import ScoreDifferenceDescription from '../../ScoreDifferenceDescription';
import useNpsChartTooltip from '../hooks/useNpsChartTooltip';

type DimensionSatisfactionHeaderProps = {
  surveyId: ManagerSurvey['id'];
  dimensionId: Topic['id'];
};

const DimensionSatisfactionHeader = ({
  surveyId,
  dimensionId,
}: DimensionSatisfactionHeaderProps) => {
  const { t } = useLokaliseTranslation('people_experience');
  const { filters } = useOutletContext<{ filters: SegmentationFilterParams }>();

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

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

  const { getTooltipTitle } = useNpsChartTooltip();

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

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

  return (
    <SatisfactionStatsHeader
      title={`${t('dimension_one')}: ${data.title}`}
      score={data.score}
      scoreLabel={t('score')}
      chartMeta={{
        title: t('answer.distribution'),
        description: `${t('answer.answer_custom_count', { count: data.answersAmount, value: formatAmount(data.answersAmount) })} | ${t('question.question_custom_count', { count: data.questionsCount, value: formatAmount(data.questionsCount) })}`,
        promoters,
        detractors,
        neutrals,
        getTooltipTitle,
      }}
      differenceIndicatorMeta={{
        baseScore: data.baseScore,
        scoreDifference: data.baseScoreDifference,
        scoreLabel: t('filter.title'),
        baseScoreLabel: t('survey.survey'),
        footerLabel: t('comparing_results'),
        getScoreDifferenceDescription: () => (
          <ScoreDifferenceDescription
            difference={data.baseScoreDifference ?? 0}
          />
        ),
      }}
      slotProps={{
        root: {
          sx: {
            ...(isPreviousData && { opacity: 0.5, pointerEvents: 'none' }),
          },
        },
      }}
    />
  );
};

export default DimensionSatisfactionHeader;
