import { useState, useEffect } from 'react';
import { useQuery } from 'react-query';

import Paper from '@material-hu/mui/Paper';
import Stack, { StackProps } from '@material-hu/mui/Stack';

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

import { getQuestionAnswers, getQuestionStats } from '../services';
import {
  ManagerSurvey,
  CommentsFilter,
  QuestionAnswersParams,
  QuestionTemplate,
  QuestionTemplateType,
} from '../types';
import { insertIf } from 'src/utils/arrays';
import { useLokaliseTranslation } from 'src/utils/i18n';

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

import CommentsList from './CommentList';
import QuestionAnswersChart from './QuestionAnswersChart';

const { ValueIndicator, DisplayGroup, DisplayGroupItem } = PeopleExperience;

type DisplayGroupItem = {
  id: string;
  value: number | string;
  label: string;
  isLoading?: boolean;
  description?: string;
};

type EngagementDashboardProps = {
  question: Pick<QuestionTemplate, 'id' | 'type'>;
  surveyId: ManagerSurvey['id'];
  sx?: StackProps['sx'];
};

const EngagementDashboard = ({
  question,
  surveyId,
  sx,
}: EngagementDashboardProps) => {
  const { t } = useLokaliseTranslation('people_experience');
  const [commentsFilter, setCommentsFilter] = useState<CommentsFilter | null>(
    null,
  );

  const params: QuestionAnswersParams = {
    formId: surveyId,
    questionId: question?.id,
    limit: 1,
    page: 1,
  };

  const answersCountQuery = useQuery(
    pxKeys.questionAnswers(params),
    () => getQuestionAnswers(params),
    { select: res => res.data.count, enabled: !!question },
  );

  const commentsCountParams = {
    ...params,
    hasComment: question?.type === QuestionTemplateType.TEXT ? undefined : true,
  };
  const commentsCountQuery = useQuery(
    pxKeys.questionAnswers(commentsCountParams),
    () => getQuestionAnswers(commentsCountParams),
    { select: res => res.data.count, enabled: !!question },
  );

  const questionStatsQuery = useQuery(
    pxKeys.questionStats({
      formId: surveyId,
      questionId: question?.id,
    }),
    () => getQuestionStats({ formId: surveyId, questionId: question?.id }),
    {
      select: res => res.data,
      enabled: !!question,
    },
  );

  const questionScore = questionStatsQuery.data?.score;

  useEffect(() => {
    if (question) {
      setCommentsFilter(null);
    }
  }, [question]);

  const displayGroupItems: DisplayGroupItem[] = [
    ...insertIf(question?.type === QuestionTemplateType.LIKERT, {
      id: 'score',
      value: questionScore ? formatValue(questionScore) : '--',
      label: t('SCORE'),
      isLoading: questionStatsQuery.isLoading,
      description: t('SCORE_DESCRIPTION'),
    }),
    {
      id: 'answers',
      value: answersCountQuery.data?.toLocaleString() ?? '--',
      label: t('answer.answers'),
      isLoading: answersCountQuery.isLoading,
    },
    {
      id: 'comments',
      value: commentsCountQuery.data?.toLocaleString() ?? '--',
      label: t('comment.comments'),
      isLoading: commentsCountQuery.isLoading,
    },
    {
      id: 'format',
      value: questionStatsQuery.data
        ? getAnswerTypeTrans({
            type: questionStatsQuery.data.type,
            t,
            scale: questionStatsQuery.data.scale,
          })
        : '--',
      label: t('ANSWER_VARIANT'),
    },
  ];

  return (
    <Stack sx={{ gap: 2, ...sx }}>
      <DisplayGroup
        items={displayGroupItems}
        renderItem={({ value, label, isLoading, description }) => (
          <DisplayGroupItem sx={{ p: 2 }}>
            <ValueIndicator
              value={value}
              label={label}
              loading={isLoading}
              description={description}
              slotProps={{
                container: { sx: { flexDirection: 'column-reverse' } },
                description: { placement: 'top' },
                value: {
                  sx: { textAlign: 'center', alignItems: 'center' },
                },
              }}
            />
          </DisplayGroupItem>
        )}
      />
      {question?.type !== 'TEXT' && (
        <Paper
          component={Stack}
          sx={{ px: 3, py: 2, gap: 2 }}
        >
          <QuestionAnswersChart
            type={question?.type}
            onSelectDatum={setCommentsFilter}
            formId={surveyId}
            questionId={question?.id}
          />
        </Paper>
      )}
      <CommentsList
        filter={commentsFilter}
        questionId={question?.id}
        questionFormat={question?.type}
        totalComments={commentsCountQuery.data ?? 0}
      />
    </Stack>
  );
};

export default EngagementDashboard;
