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

import { once } from 'lodash-es';
import Stack from '@material-hu/mui/Stack';

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

import { logEvent } from 'src/config/amplitude';
import { pxKeys } from '../../../../queries';
import { formatValue } from '../../../../utils';
import { formatAmount } from '../../../../utils/formatting';
import { getParticipationStats } from '../../../../services';
import { EventName } from 'src/types/amplitude';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { type ManagerResultsOutletContext } from '../../types';

import ParticipationDashboard from './components/ParticipationDashboard';

const { SurveyParticipationHeader } = PeopleExperience;

const ParticipationResults = () => {
  const { t } = useLokaliseTranslation('people_experience');
  const { survey } = useOutletContext<ManagerResultsOutletContext>();
  const surveyId = survey.id;
  const logEventOnce = useMemo(() => once(logEvent), []);

  useEffect(() => {
    if (surveyId) {
      logEventOnce(EventName.PARTICIPATION_VIEWED, { surveyID: surveyId });
    }
  }, [logEventOnce, surveyId]);

  const query = useQuery(
    pxKeys.participationStats(surveyId),
    () => getParticipationStats(surveyId),
    {
      select: res => res.data,
    },
  );

  const data = query.data ?? { pending: 1, total: 1 };
  const completionCount = data.total - data.pending;

  return (
    <Stack
      sx={{
        p: 3,
        gap: 3,
        overflowY: 'auto',
        flex: 1,
        borderLeft: theme =>
          `1px solid ${theme.palette.new.border.neutral.divider}`,
      }}
    >
      <SurveyParticipationHeader
        participationRate={formatValue((1 - data.pending / data.total) * 100)}
        completedCount={completionCount}
        isLoading={query.isLoading}
        labels={{
          participation: t('participation.title'),
          answers: t('answer.answers'),
          total: t('participation_ratio', {
            value: formatAmount(completionCount),
            total: formatAmount(data.total),
            count: data.total,
          }),
          sendReminder: t('SEND_REMINDER'),
        }}
      />
      <ParticipationDashboard />
    </Stack>
  );
};

export default ParticipationResults;
