import api from 'src/config/api';
import {
  type ColabListItem,
  type ColabsMetrics,
  type CourseDetail,
  type CourseListItem,
  type CourseOnPathResponse,
  type CoursesListParams,
  type CoursesMetrics,
  type CreateCourseCategoryParams,
  type CreateCourseData,
  type CreateDraftData,
  type DownloadReportParams,
  type EditCourseAudienceData,
  type EditCourseStatusData,
  type EvaluationListItem,
  type GetColabsParams,
  type GetEvaluationReportData,
  type SurveyListItem,
  type SurveysMetrics,
  type UpdateCourseData,
} from 'src/pages/dashboard/Learning/Courses/types';
import {
  type SortingOrderType,
  type TableColumnsType,
} from 'src/pages/dashboard/Learning/common/types';
import { getSortingOption } from 'src/pages/dashboard/Learning/common/utils';
import { type Category } from 'src/pages/dashboard/Learning/Settings/Categories/types';
import { type Audience } from 'src/types/segmentation';
import {
  formatPagination,
  type PaginatedResponse,
  type Pagination,
} from 'src/utils/tableUtils';

export const getCoursesMetrics = () => api.get<CoursesMetrics>('courses/stats');

export const getCourseOnPath = (id: number) =>
  api.get<CourseOnPathResponse>(`courses/${id}/learning-paths/exists`);

export const getEvaluations = (
  id: number | string,
  { search, ...pagination }: Pagination,
) =>
  api.get<PaginatedResponse<EvaluationListItem>>(`courses/${id}/evaluations`, {
    params: {
      search: search || undefined,
      ...formatPagination(pagination),
    },
  });

export const getCourseAudience = (id: number) =>
  api.get<Audience>(`courses/${id}/audience`);

export const getEvaluationReport = (data: GetEvaluationReportData) =>
  api.get('courses/tasks/evaluations/report', {
    params: {
      ...data,
      groupIds: data?.groupIds?.toString(),
      userFields: data?.userFields?.toString(),
    },
    responseType: 'blob',
  });

export const getColabs = (id: number, params: GetColabsParams) =>
  api.get<PaginatedResponse<ColabListItem>>(`courses/${id}/users-progress`, {
    params: {
      userName: params.search || undefined,
      status: params.status || undefined,
      ...formatPagination(params),
    },
  });

export const getColabsMetrics = (id: number | string) =>
  api.get<ColabsMetrics>(`courses/${id}/stats`);

export const getSurveysMetrics = (id: number | string) =>
  api.get<SurveysMetrics>(`courses/${id}/survey-stats`);

export const getCourse = (id: number | string) =>
  api.get<CourseDetail>(`courses/${id}`);

export const getCourses = (pagination: Partial<CoursesListParams>) => {
  const { sortingOption } = getSortingOption(
    pagination.order as SortingOrderType,
    pagination.orderBy as TableColumnsType,
  );

  const params: Partial<CoursesListParams> = {
    ...pagination,
    sortingOption,
  };

  return api.get<PaginatedResponse<CourseListItem>>('courses', { params });
};

export const downloadBulkCertificates = (
  courseId: number,
  email: string,
  segmentationItemIds?: number[],
  segmentationUserIds?: number[],
) => {
  const params = new URLSearchParams({ email });
  if (segmentationItemIds?.length) {
    params.set('segmentationItemIds', segmentationItemIds.join(','));
  }
  if (segmentationUserIds?.length) {
    params.set('segmentationUserIds', segmentationUserIds.join(','));
  }
  return api.post(`courses/${courseId}/cert/zip?${params.toString()}`);
};

export const downloadReport = ({
  courseId,
  email,
  isAttendanceReport,
  includeGroups = [],
  includeUserFields = [],
}: DownloadReportParams) => {
  const params: Record<string, string> = { email };

  if (includeGroups.length > 0) {
    params.groupIds = includeGroups.join(',');
  }

  if (includeUserFields.length > 0) {
    params.userFields = includeUserFields.join(',');
  }

  const commonPath = `courses/${courseId}/users-progress`;

  const url = isAttendanceReport
    ? `${commonPath}/attendance-report`
    : `${commonPath}/report`;

  return api.get<BlobPart>(url, { params });
};

export const getSurveys = (
  id: number | string,
  { search, ...pagination }: Pagination,
) =>
  api.get<PaginatedResponse<SurveyListItem>>(`courses/${id}/survey-comments`, {
    params: {
      search: search || undefined,
      ...formatPagination(pagination),
    },
  });

export const getCourseCategories = ({ order, ...pagination }: Pagination) => {
  return api.get<PaginatedResponse<Category>>('courses/categories', {
    params: {
      includeCourses: false,
      sortingOption: order,
      ...formatPagination(pagination),
    },
  });
};

export const createCourse = (data: CreateCourseData) =>
  api.post<CourseDetail>('courses', data);

export const createCourseCategory = (params: CreateCourseCategoryParams) =>
  api.post<Category>('courses/categories', params);

export const resetCourseProgress = (courseId: number, colabId: number) =>
  api.post(`courses/${courseId}/users-progress/reset/${colabId}`);

export const forceCourseCompletion = (courseId: number, userId: number) =>
  api.post(`courses/${courseId}/users/${userId}/completion`);

export const notifyCourseAudience = (id: number) =>
  api.post(`courses/${id}/audience/notify-pending`);

export const duplicateCourse = (id: number | string) =>
  api.post<CourseDetail>(`courses/${id}/duplication`);

export const createDraft = (data: CreateDraftData) =>
  api.post<CourseDetail>('courses/draft', data);

//// PUT ////
export const editCourseAudience = (id: number, data: EditCourseAudienceData) =>
  api.put(`courses/${id}/audience`, data);

export const editCourseStatus = (id: number, data: EditCourseStatusData) =>
  api.put(`courses/${id}/status`, data);

export const editCourse = (id: number, data: CreateCourseData) =>
  api.put(`courses/${id}`, data);

//// DELETE ////
export const deleteCourse = (id: number) => api.delete(`courses/${id}`);

export const deleteTask = (courseId: number, taskId: number) =>
  api.delete(`courses/${courseId}/tasks/${taskId}`);

export const deleteModule = (courseId: number, moduleId: number) =>
  api.delete(`courses/${courseId}/modules/${moduleId}`);

//// PATCH ////
export const updateCourse = (id: number, data: UpdateCourseData) =>
  api.patch<CourseDetail>(`courses/${id}`, data);
