import { format, formatDuration, intervalToDuration } from 'date-fns';

import { FileExtensions } from 'src/constants/filesPreview';
import { formatDateInTimezone } from 'src/utils/date';
import { capitalizeFirstLetter } from 'src/utils/text';

export const formatDurationLivestream = (
  start: string | number | undefined,
  end: string | number | undefined,
  locale: Locale,
) => {
  if (typeof start === 'undefined' || typeof end === 'undefined') return '-';

  // If number convert seconds to milliseconds
  const duration = intervalToDuration({
    start: typeof start === 'number' ? start * 1000 : new Date(start),
    end: typeof end === 'number' ? end * 1000 : new Date(end),
  });

  const { hours, minutes } = duration;

  return formatDuration(duration, {
    format: !hours && !minutes ? ['seconds'] : ['hours', 'minutes'],
    locale,
  });
};

export const formatStartedAtLivestream = (
  startedAt: string | undefined,
  locale: Locale,
) => {
  if (!startedAt) return '-';

  return capitalizeFirstLetter(
    format(new Date(startedAt), 'EEE, d MMM yyyy', { locale }),
  );
};

export const formatStartTimetLivestream = (
  startedAt: string | undefined,
  timezone: string | undefined,
) => {
  if (!startedAt) return '-';
  if (!timezone) return format(new Date(startedAt), 'HH:mm');

  const transformedDateInTimezone = formatDateInTimezone(startedAt, timezone);
  return format(new Date(transformedDateInTimezone), 'HH:mm');
};

export const getLabelInterval = (length: number, interval: number) => {
  if (length <= 30 / interval + 1) return 5;
  if (length <= 60 / interval + 1) return 10;
  if (length <= 120 / interval + 1) return 20;
  if (length <= 180 / interval + 1) return 30;
  if (length <= 240 / interval + 1) return 40;

  return 60;
};

export const getDownloadLiveReportName = (postDate: string, postId: string) => {
  return `LivestreamMetrics_${format(new Date(postDate), 'ddMMyyyy')}_${postId}.${FileExtensions.XLSX}`;
};
