import { format, isSameDay } from 'date-fns';
import { enUS, hu } from 'date-fns/locale';

import { toBudapestDate } from '@/utils/eventHelpers';

import { Event } from '@/types/Events';

export const formatEventShortDate = (event: Event, locale: string): string => {
  const startDate = toBudapestDate(event.kezdete);
  if (Number.isNaN(startDate.getTime())) return '';
  const isEn = locale.toLowerCase().startsWith('en');
  const dateLocale = isEn ? enUS : hu;
  const includeTime = !event.kezdeteDatum;
  const shortStartFormatString = includeTime
    ? isEn
      ? 'MMM d, HH:mm'
      : 'MMM d. HH:mm'
    : isEn
      ? 'MMM d'
      : 'MMM d.';
  const intervalStartFormatString = includeTime
    ? isEn
      ? 'MMM d, yyyy, HH:mm'
      : 'yyyy. MMM d. HH:mm'
    : isEn
      ? 'MMM d, yyyy'
      : 'yyyy. MMM d.';
  const shortStartLabel = format(startDate, shortStartFormatString, {
    locale: dateLocale,
  });

  if (!event.vege) return shortStartLabel;

  const endDate = toBudapestDate(event.vege);
  if (Number.isNaN(endDate.getTime()) || isSameDay(startDate, endDate)) {
    return shortStartLabel;
  }

  const startLabel = format(startDate, intervalStartFormatString, {
    locale: dateLocale,
  });
  const includeEndTime = !event.vegeDatum;
  const endFormatString = includeEndTime
    ? isEn
      ? 'MMM d, yyyy, HH:mm'
      : 'yyyy. MMM d. HH:mm'
    : isEn
      ? 'MMM d, yyyy'
      : 'yyyy. MMM d.';
  const endLabel = format(endDate, endFormatString, { locale: dateLocale });

  return `${startLabel} - ${endLabel}`;
};
