import { type User } from 'src/types/user';
import { type TCustomFunction } from 'src/utils/i18n';
import { getFullname } from 'src/utils/userUtils';

import { type NewPathFormValues } from '../Paths/types';
import { type NewSessionFormValues } from '../Sessions/types';

import {
  type LearningAudience,
  type LearningDuration,
  type SegmentationCondition,
  type SegmentationPayload,
  type SortingOptionsType,
  type SortingOrderType,
  type TableColumnsType,
} from './types';

const MAX_COLLABORATORS_LIMIT = 10;

/**
 * Gets a sorting option for a table column.
 */
export const getSortingOption = (
  order: SortingOrderType,
  orderBy: TableColumnsType,
) => {
  let sortingOption: SortingOptionsType | undefined;

  if (orderBy === 'title') {
    sortingOption = order === 'ASC' ? 'TITLE_ASC' : 'TITLE_DESC';
  }

  if (orderBy === 'createdAt') {
    sortingOption = order === 'ASC' ? 'LAST_UPDATE_ASC' : 'LAST_UPDATE_DESC';
  }

  return { sortingOption };
};

/**
 * Builds a list of individual users for a segmentation condition.
 */
export const buildIndividualUsersList = (
  users: Partial<User>[],
  limit: number = MAX_COLLABORATORS_LIMIT,
) => {
  if (!users || !users.length) return null;

  const usersList = users
    .map(user => getFullname(user))
    .slice(0, limit)
    .join(', ');

  const extraCount = users.length > limit ? `, + ${users.length - limit}` : '';

  return {
    titleKey: 'common.segmentation_type.user',
    list: usersList,
    extraCount,
  };
};

/**
 * Builds a list of group segmentations for a segmentation condition.
 */
export const buildGroupSegmentationList = (
  segmentations: Record<string, string[]>,
  limit: number = MAX_COLLABORATORS_LIMIT,
) => {
  const segmentationsList = Object.entries(segmentations).map(
    ([group, items]) => `${group}: ${items.join(', ')}`,
  );

  const sectionsList = segmentationsList.slice(0, limit).join(' / ');

  const extraCount =
    segmentationsList.length > limit
      ? `, +${segmentationsList.length - limit}`
      : '';

  return {
    titleKey: 'common.segmentation_type.group',
    list: sectionsList,
    extraCount,
  };
};

/**
 * Formats a learning segmentation for a form values.
 */
export const formatLearnignSegmentation = (
  formValues: NewSessionFormValues | NewPathFormValues,
): SegmentationPayload => {
  const conditions: SegmentationCondition[] = [];

  if (formValues.segmentation) {
    conditions.push({
      type: 'USERS_OR_ITEMS',
      userIds: formValues.segmentation.userSegmentation.map(user => user.id!),
      segmentationItemIds: formValues.segmentation.groupSegmentation,
    });
  } else conditions.push({ type: 'ALL' });

  return { segmentationExpressions: { conditions } };
};

/**
 * Formats an audience for a form values.
 */
export const formatLearningAudience = (audience?: LearningAudience) => {
  if (!audience || audience.isPublic || !audience.isAudienceDefined) {
    return null;
  }

  return {
    userSegmentation: audience.segmentationUsers,
    groupSegmentation: audience.segmentationItemIds,
  };
};

export const getDurationTime = (
  t: TCustomFunction,
  durationTime?: LearningDuration,
  showZeroHours?: boolean,
): string => {
  if (!durationTime) return '';

  const { hours = 0, minutes = 0 } = durationTime;
  const minuteText = t('general:minutes_long');
  const hourText = t('general:hours_short');

  if (!hours && !minutes) return showZeroHours ? `0 ${hourText}` : '';

  const parts: string[] = [];
  if (hours) parts.push(`${hours} ${hourText}`);
  if (minutes) parts.push(`${minutes} ${minuteText}`);

  return parts.join(' ');
};
