import { format, parseISO, type Locale } from 'date-fns';

import { EntrySource, type TimeOffRequest } from 'src/types/timeTracking';
import { type LokaliseTFunction } from 'src/utils/i18n';

export const truncateTimeToHHMM = (time: string) => time.slice(0, 5);

export const HOLIDAY_TYPE = 'HOLIDAY' as const;
export const TIME_OFF_TYPE = 'TIME_OFF' as const;

export const SOURCE_TOOLTIP_KEYS: Partial<Record<EntrySource, string>> = {
  [EntrySource.APP]: 'time_tracker:settings.humand_app',
  [EntrySource.KIOSK]: 'time_tracker:settings.humand_kiosk',
  [EntrySource.WEB]: 'time_tracker:settings.humand_web',
  [EntrySource.MANUAL]: 'time_tracker:source_tooltip_manual',
  [EntrySource.SYSTEM]: 'time_tracker:marking_source_system',
  [EntrySource.INTEGRATION]: 'time_tracker:marking_source_integration',
};

export const CONSUMPTION = {
  FULL_DAY: 'FULL_DAY',
  HALF_DAY: 'HALF_DAY',
  HOURS: 'HOURS',
} as const;

export const ACTIVITY = {
  WORK: 'WORK',
} as const;

export const isPeriodTimeOff = (request: TimeOffRequest | undefined) =>
  request?.consumptionType === CONSUMPTION.FULL_DAY &&
  request.fromDate &&
  request.toDate &&
  request.fromDate !== request.toDate;

export const formatShortDateRange = (
  from: string,
  to: string,
  locale: Locale,
  t: LokaliseTFunction,
) => {
  const startDate = format(parseISO(from), 'd MMM', { locale });
  const endDate = format(parseISO(to), 'd MMM', { locale });
  return t('time_tracking_common:dates_from_to', { startDate, endDate });
};

export const getTimeOffPillLabel = (
  request: TimeOffRequest,
  isPeriod: boolean,
  t: LokaliseTFunction,
  locale: Locale,
) => {
  if (request.consumptionType === CONSUMPTION.HALF_DAY) {
    return t('time_tracking_common:time_offs_permits.half_day');
  }
  const label = t('time_tracker:permission_label');
  if (
    request.consumptionType === CONSUMPTION.HOURS &&
    request.fromTime &&
    request.toTime
  ) {
    return `${label}: ${t('time_tracking_common:hours_from_to', {
      startHour: truncateTimeToHHMM(request.fromTime ?? ''),
      endHour: truncateTimeToHHMM(request.toTime ?? ''),
    })}`;
  }
  if (isPeriod && request.fromDate && request.toDate) {
    return `${label}: ${formatShortDateRange(request.fromDate, request.toDate, locale, t)}`;
  }
  return label;
};
