import {
  ColabStatus,
  type SurveyQuestion,
  SurveyQuestions,
  type SurveysMetrics,
} from 'src/pages/dashboard/Learning/Courses/types';

import { Severities } from 'src/components/SeverityPill/types';

import {
  CHOICE_YES_TITLES,
  CONTENT_RATING_QUESTION_TITLES,
  RECOMMENDATION_QUESTION_TITLES,
} from './constants';

export const getSeverity = (status: ColabStatus) => {
  if (!status) return Severities.RECOMMENDED;

  if (status === ColabStatus.PENDING) return Severities.WARNING;
  if (status === ColabStatus.EXPIRED) return Severities.ERROR;
  if (status === ColabStatus.FINISHED) return Severities.SUCCESS;
  if (status === ColabStatus.PENDING_SIGNATURE) return Severities.SIMPLE;

  return Severities.RECOMMENDED;
};

export const formatNumber = (
  value: number | string | undefined,
  minimumFractionDigits = 0,
  maximumFractionDigits = 2,
  locales = undefined,
) => {
  if (value === undefined || value === null) return '--';

  return value.toLocaleString(locales, {
    minimumFractionDigits,
    maximumFractionDigits,
  });
};

// We have the survey questions hardcoded for now.
export const getSurveyQuestionType = (question: SurveyQuestion) => {
  if (!question) return null;

  if (RECOMMENDATION_QUESTION_TITLES.includes(question.title)) {
    return SurveyQuestions.RECOMMENDATION;
  }

  if (CONTENT_RATING_QUESTION_TITLES.includes(question.title)) {
    return SurveyQuestions.CONTENT_RATING;
  }

  return SurveyQuestions.EXPERIENCE_RATING;
};

export const getRecommendationMetrics = (
  surveyMetrics: SurveysMetrics | undefined,
) => {
  if (!surveyMetrics?.questionAnswers) return undefined;

  const recommendedMetrics = surveyMetrics.questionAnswers.find(
    question =>
      getSurveyQuestionType(question) === SurveyQuestions.RECOMMENDATION &&
      CHOICE_YES_TITLES.includes(question.answer),
  );

  if (!recommendedMetrics) return undefined;

  return recommendedMetrics.score;
};

export const getRatingMetrics = (
  metrics: SurveysMetrics | undefined,
  type: SurveyQuestions,
) => {
  const ratingMetrics: number[] = Array(5).fill(0);

  if (!metrics?.questionAnswers?.length) return ratingMetrics;

  metrics.questionAnswers.forEach(question => {
    if (getSurveyQuestionType(question) !== type) return;

    const rating = Number(question.answer);
    ratingMetrics[rating - 1] = question.score;
  });

  return ratingMetrics;
};
