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

import { once } from 'lodash-es';

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

import { logEvent } from 'src/config/amplitude';
import { getParticipationStats } from '../services';
import { EventName } from 'src/types/amplitude';
import { useLokaliseTranslation } from 'src/utils/i18n';

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

import ParticipationDashboard from './ParticipationDashboard';

const { DisplayGroup, DisplayGroupItem, ResultContainer, ValueIndicator } =
  PeopleExperience;

const ParticipationTab = () => {
  const { t } = useLokaliseTranslation('people_experience');
  const urlParams = useParams();
  const surveyId = Number(urlParams.id);
  const logEventOnce = useMemo(() => once(logEvent), []);

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

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

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

  return (
    <ResultContainer title={t('participation.title')}>
      <DisplayGroup
        items={[
          {
            id: 'participation',
            value: `${formatValue((1 - data.pending / data.total) * 100)}%`,
            label: t('participation.title'),
          },
          {
            id: 'employees',
            value: completionCount,
            label: t('answer.answers'),
            description: t('PARTICIPATION_RATIO', {
              count: completionCount,
              total: data.total,
            }),
          },
        ]}
        renderItem={({ value, label, description }) => (
          <DisplayGroupItem sx={{ p: 4 }}>
            <ValueIndicator
              value={value}
              label={label}
              description={description}
              loading={isLoading}
            />
          </DisplayGroupItem>
        )}
      />
      <ParticipationDashboard />
    </ResultContainer>
  );
};

export default ParticipationTab;
