import { THEME_COLORS } from 'src/constants/scorm';
import { ScormProgressType } from 'src/types/scorm';
import { type MeUser } from 'src/types/user';

export const formatCourseRegistrationData = (
  courseId: string,
  user: MeUser,
) => {
  const learner = {
    id: user.id,
    email: user.email,
    firstName: user.firstName,
    lastName: user.lastName,
  };

  return {
    courseId: courseId,
    learner: learner,
    registrationId: `${courseId}-${user.id}`,
  };
};

export const addRegistrationStatus = (courses, registrations) =>
  courses?.map((value, index) => {
    const registrationData = registrations[index]?.data?.data?.registrations;

    return {
      ...value,
      registerData:
        registrationData?.length > 0
          ? {
              registrationCompletion:
                registrationData[0].registrationCompletion || null,
              registrationSuccess:
                registrationData[0].registrationSuccess || null,
              score: registrationData[0].score
                ? registrationData[0].score.scaled
                : null,
            }
          : null,
    };
  });

export const getGroupCourses = courses => {
  const groupedCourses = [];

  courses?.forEach(course => {
    const theme = course.tags.find(tag => /[a-zA-Z]/.test(tag));
    if (theme) {
      let group = groupedCourses.find(g => g.name === theme);
      if (!group) {
        const index = groupedCourses.length;
        const color = THEME_COLORS[index % THEME_COLORS.length];
        group = { name: theme, courses: [], color: color };
        groupedCourses.push(group);
      }
      group.courses.push(course);
    }
  });

  return groupedCourses;
};

export const getThemes = folders => folders.map(folder => folder.name);

export const getActiveFilters = data =>
  Object.keys(data).filter(key => data[key] === true);

export const getCoursesByTitle = (title, search) =>
  title.toLowerCase().includes(search.toLowerCase());

export const getCoursesByFilters = (filters, folderName) =>
  filters.length === 0 || filters.some(filter => folderName.includes(filter));

export const getCoursesByState = (filters, state, t) => {
  const courseState = state
    ? t(state.registrationCompletion)
    : t(ScormProgressType.UNKNOWN);
  return filters.length === 0 || filters.some(filter => courseState === filter);
};
