import { getAnswerTypeTrans } from '../../../../../../utils';
import { distributeRoundedPercentages } from '../../../../../../utils/formatting';
import {
  FavQuestionsStatsResponse,
  QuestionTemplateType,
} from '../../../../../../types';
import { LokaliseTFunction } from 'src/utils/i18n';

import { getCountDescription } from '../../utils';

import {
  ParsedQuestionStats,
  ParsedSelectQuestionStats,
  SELECT_QUESTION_TYPE,
} from './types';

export const parseQuestionStatsToTableFormat = (
  item: FavQuestionsStatsResponse,
  t: LokaliseTFunction,
): ParsedQuestionStats => {
  const baseData = {
    id: item.id,
    statement: item.title,
    topicLabel: item.topic.title,
    answersLabel: getCountDescription(
      'answer.answer_custom_count',
      item.answersAmount,
      t,
    ),
    answersAmount: item.answersAmount,
    commentsAmount: item.commentsAmount,
    hasThresholdPassed: item.passedThreshold,
    commentsLabel: getCountDescription(
      'comment.comment_custom_count',
      item.commentsAmount,
      t,
    ),
    typeLabel: getAnswerTypeTrans({ t, type: item.type, scale: item.scale }),
    baseScore: item.baseScore,
    scoreDifference: item.baseScoreDifference,
  };

  switch (item.type) {
    case QuestionTemplateType.LIKERT: {
      const [promoters, detractors, neutrals] = distributeRoundedPercentages([
        item.metadata?.promoters ?? 0,
        item.metadata?.detractors ?? 0,
        item.metadata?.neutrals ?? 0,
      ]);
      return {
        ...baseData,
        score: item.score as number,
        type: item.type,
        promoters,
        detractors,
        neutrals,
      };
    }
    case QuestionTemplateType.TEXT:
      return {
        ...baseData,
        score: null,
        type: item.type,
      };
    case QuestionTemplateType.CHECKBOX:
    case QuestionTemplateType.MULTIPLE_CHOICE:
      const selectData: ParsedSelectQuestionStats = {
        ...baseData,
        score: null,
        type: SELECT_QUESTION_TYPE,
        answer: item.metadata?.option!,
        scorePercentage: Math.round(item.metadata?.rate! * 100),
      };
      return selectData;
  }
};
