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

import { isEmpty, negate } from 'lodash-es';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import DistributionStats from '@material-hu/components/composed-components/peopleExperience/npsResults/components/DistributionStats';
import EnpsTotal from '@material-hu/components/composed-components/peopleExperience/npsResults/components/EnpsTotal';
import ScoreDifferenceIndicator from '@material-hu/components/composed-components/peopleExperience/surveyResults/ScoreDifferenceIndicator';

import { pxKeys } from '../../../../queries';
import { getEnpsScores } from '../../../../services';
import {
  type EnpsScoresParams,
  type SegmentationFilterParams,
  type TransformedManagerSurvey,
} from '../../../../types';
import { useLokaliseTranslation } from 'src/utils/i18n';

import ScoredifferenceDescription from '../ScoreDifferenceDescription';

import CommentList from './components/CommentsTableList';
import EnpsChartSection from './components/EnpsChartSection';
import { getStatDisplayText } from './utils';

const EnpsResults = () => {
  const { t } = useLokaliseTranslation('people_experience');
  const { filters, survey } = useOutletContext<{
    filters: SegmentationFilterParams;
    survey: TransformedManagerSurvey;
  }>();

  const eNpsScoresParams: EnpsScoresParams = {
    surveyId: survey.id,
    ...filters,
  };

  const {
    data: scoreData,
    isLoading: isLoadingScoreData,
    isPreviousData: isPreviousScoreData,
  } = useQuery(
    pxKeys.eNpsScores(eNpsScoresParams),
    () => getEnpsScores(eNpsScoresParams),
    {
      select: response => response.data,
      keepPreviousData: true,
    },
  );

  const hasSegmentationFilters = Object.values(filters).some(negate(isEmpty));

  const isThresholdMet = scoreData?.passedThreshold;
  const scoreDifference = scoreData?.baseStats?.baseScoreDifference ?? 0;

  const distributionStats = scoreData
    ? [
        {
          type: 'promoter' as const,
          title: t('promoters'),
          value: getStatDisplayText(
            scoreData.statsPercentage.PROMOTERS,
            t,
            isThresholdMet,
          ),
          score: scoreData.statsPercentage.PROMOTERS,
          baseScore: scoreData.baseStats?.statsPercentage.PROMOTERS,
          difference: scoreData.baseStats?.statsPercentageDifference.PROMOTERS,
        },
        {
          type: 'neutral' as const,
          title: t('neutral'),
          value: getStatDisplayText(
            scoreData.statsPercentage.NEUTRALS,
            t,
            isThresholdMet,
          ),
          score: scoreData.statsPercentage.NEUTRALS,
          baseScore: scoreData.baseStats?.statsPercentage.NEUTRALS,
          difference: scoreData.baseStats?.statsPercentageDifference.NEUTRALS,
        },
        {
          type: 'detractor' as const,
          title: t('detractors'),
          value: getStatDisplayText(
            scoreData.statsPercentage.DETRACTORS,
            t,
            isThresholdMet,
          ),
          score: scoreData.statsPercentage.DETRACTORS,
          baseScore: scoreData.baseStats?.statsPercentage.DETRACTORS,
          difference: scoreData.baseStats?.statsPercentageDifference.DETRACTORS,
        },
      ]
    : [];

  return (
    <Stack
      sx={{
        p: 3,
        gap: 3,
        overflowY: 'auto',
        width: '100%',
        opacity: isPreviousScoreData ? 0.5 : 1,
      }}
    >
      <Stack sx={{ flexDirection: 'row', gap: 2 }}>
        <EnpsTotal
          title={t('nps_total')}
          description={t('survey_dashboard.e_nps.extended_description')}
          value={scoreData?.score ?? null}
          footer={
            hasSegmentationFilters && scoreData ? (
              <Typography
                component={Stack}
                sx={{ flexDirection: 'row', gap: 1 }}
              >
                <ScoreDifferenceIndicator
                  difference={scoreData.baseStats?.baseScoreDifference}
                  popoverMeta={{
                    baseScore: scoreData.baseStats?.score,
                    score: scoreData.score,
                    baseScoreLabel: t('survey.survey'),
                    scoreLabel: t('filter.title'),
                    footerLabel: t('comparing_results'),
                    scoreDifferenceDescription: (
                      <ScoredifferenceDescription
                        difference={scoreDifference}
                      />
                    ),
                  }}
                  slotProps={{
                    popover: {
                      anchorOrigin: {
                        vertical: 'top',
                        horizontal: 48,
                      },
                      transformOrigin: {
                        vertical: 'top',
                        horizontal: 'left',
                      },
                    },
                  }}
                />
                {scoreData.baseStats?.baseScoreDifference && (
                  <span>{t('e_nps.regarding_applied_filter')}</span>
                )}
              </Typography>
            ) : undefined
          }
          nullValueTooltip={t('not_enough_data_title')}
        />
        <DistributionStats
          title={t('distribution')}
          stats={distributionStats.map(stat => ({
            type: stat.type,
            title: stat.title,
            value: stat.value,
            differenceIndicator: (
              <ScoreDifferenceIndicator
                difference={stat.difference}
                popoverMeta={{
                  baseScore: stat.baseScore,
                  score: stat.score,
                  baseScoreLabel: t('survey.survey'),
                  scoreLabel: t('filter.title'),
                  footerLabel: t('comparing_results'),
                  scoreDifferenceDescription: (
                    <ScoredifferenceDescription difference={stat.difference} />
                  ),
                }}
                slotProps={{
                  popover: {
                    anchorOrigin: {
                      vertical: 24,
                      horizontal: 'right',
                    },
                    transformOrigin: {
                      vertical: 'top',
                      horizontal: 'right',
                    },
                  },
                }}
              />
            ),
          }))}
          sx={{ maxWidth: 720 }}
          loading={isLoadingScoreData}
        />
      </Stack>
      <EnpsChartSection
        surveyId={survey.id}
        filters={filters}
        isLoadingScoreData={isLoadingScoreData}
      />
      <CommentList />
    </Stack>
  );
};

export default EnpsResults;
