import {isToday} from 'date-fns/isToday';
import {isYesterday} from 'date-fns/isYesterday';
import i18next from '@config/i18n';
import {PinDuration} from '@modules/chats/constants';
import {
  addDays,
  addHours,
  addMinutes,
  capitalize,
  format,
  getCurrentLocale,
  getDifferenceInDays,
  getFormattedDate,
  getTimeFromUlid,
} from '@shared/utils';

export const getLocalizedDateLabelByTs = (ts: string) => {
  const date = getTimeFromUlid(ts);

  let label = '';
  if (isToday(date)) {
    label = i18next.t('general.today');
  } else if (isYesterday(date)) {
    label = i18next.t('general.yesterday');
  } else if (getDifferenceInDays(date) < 7) {
    label = getFormattedDate(date, 'EEEE', {locale: getCurrentLocale()});
  } else {
    label = getFormattedDate(date, 'EEE, LLL dd', {
      locale: getCurrentLocale(),
    });
  }
  return capitalize(label)!;
};

export const getHumanizedDateWithTime = (
  timestamp?: number | string | Date,
) => {
  const date = timestamp ? new Date(timestamp) : new Date();
  const time = format(date, 'HH:mm', {locale: getCurrentLocale()});
  const dateLabel = isToday(date)
    ? i18next.t('general.today')
    : isYesterday(date)
    ? i18next.t('general.yesterday')
    : getFormattedDate(date, 'dd/MM/yyyy', {locale: getCurrentLocale()});

  return {
    date: dateLabel,
    time,
  };
};

export const getDateFromULID = (ulid: string) => {
  return new Date(getTimeFromUlid(ulid));
};

const PIN_ALWAYS_DAYS = 500 * 365;

export function getExpiresAtForPinDuration(duration: PinDuration): string {
  const now = Date.now();
  switch (duration) {
    case '1m':
      return addMinutes(now, 1).getTime().toString();
    case '24h':
      return addHours(now, 24).getTime().toString();
    case '30d':
      return addDays(now, 30).getTime().toString();
    case 'always':
      return addDays(now, PIN_ALWAYS_DAYS).getTime().toString();
    default:
      return addDays(now, PIN_ALWAYS_DAYS).getTime().toString();
  }
}
