import { format, formatDistanceToNow, parseISO, isValid, isToday } from 'date-fns';
import { de } from 'date-fns/locale';

/**
 * Parse a date string or Date object into a valid Date, or null if invalid/empty.
 */
function toDate(value: string | Date | null | undefined): Date | null {
  if (value === null || value === undefined || value === '') return null;
  if (value instanceof Date) return isValid(value) ? value : null;
  const parsed = parseISO(value);
  return isValid(parsed) ? parsed : null;
}

/**
 * Format a date with a custom date-fns pattern and German locale.
 * Returns empty string for null/undefined/invalid dates.
 */
export function formatDate(date: string | Date | null | undefined, pattern: string): string {
  const d = toDate(date);
  if (!d) return '';
  return format(d, pattern, { locale: de });
}

/**
 * Standard date + time format: dd.MM.yyyy HH:mm
 */
export function formatDateTime(date: string | Date | null | undefined): string {
  return formatDate(date, 'dd.MM.yyyy HH:mm');
}

/**
 * Short date format: dd.MM.yyyy
 */
export function formatDateShort(date: string | Date | null | undefined): string {
  return formatDate(date, 'dd.MM.yyyy');
}

/**
 * Time only format: HH:mm
 */
export function formatTime(date: string | Date | null | undefined): string {
  return formatDate(date, 'HH:mm');
}

/**
 * Relative time format: "vor 5 Minuten", "in 2 Stunden"
 */
export function formatRelative(date: string | Date | null | undefined): string {
  const d = toDate(date);
  if (!d) return '';
  return formatDistanceToNow(d, { locale: de, addSuffix: true });
}

/**
 * Month + day format: "15. Juli"
 */
export function formatMonthDay(date: string | Date | null | undefined): string {
  return formatDate(date, 'd. MMMM');
}

/**
 * Smart date: shows time (HH:mm) if today, otherwise short date (d. MMM).
 * Used in mail list and similar compact views.
 */
export function formatSmartDate(date: string | Date | null | undefined): string {
  const d = toDate(date);
  if (!d) return '';
  if (isToday(d)) {
    return format(d, 'HH:mm', { locale: de });
  }
  return format(d, 'd. MMM', { locale: de });
}

/**
 * Date input format for <input type="date">: yyyy-MM-dd
 */
export function formatDateInput(date: string | Date | null | undefined): string {
  return formatDate(date, 'yyyy-MM-dd');
}

/**
 * DateTime input format for <input type="datetime-local">: yyyy-MM-ddTHH:mm
 */
export function formatDateTimeInput(date: string | Date | null | undefined): string {
  return formatDate(date, "yyyy-MM-dd'T'HH:mm");
}
