import { localCalendarOrdinal, parseDateValue } from './dateParsing';

export function formatDetailDate(value?: string | null): string {
  const date = parseDateValue(value);
  return date ? date.toLocaleDateString() : 'Not available';
}

function formatPastDistance(days: number): string {
  if (days === 1) return 'Yesterday';
  if (days < 7) return `${days} days ago`;

  const weeks = Math.floor(days / 7);
  if (weeks === 1) return '1 week ago';
  if (weeks < 5) return `${weeks} weeks ago`;

  const months = Math.floor(days / 30);
  if (months === 1) return '1 month ago';
  if (months < 12) return `${months} months ago`;

  const years = Math.floor(days / 365);
  return years === 1 ? '1 year ago' : `${years} years ago`;
}

function formatFutureDistance(days: number): string {
  if (days === 1) return 'Tomorrow';
  if (days < 7) return `In ${days} days`;

  const weeks = Math.floor(days / 7);
  if (weeks === 1) return 'In 1 week';
  if (weeks < 5) return `In ${weeks} weeks`;

  const months = Math.floor(days / 30);
  if (months === 1) return 'In 1 month';
  if (months < 12) return `In ${months} months`;

  const years = Math.floor(days / 365);
  return years === 1 ? 'In 1 year' : `In ${years} years`;
}

export function formatRelativeDate(value?: string | null): string {
  const date = parseDateValue(value);
  if (!date) return '';

  const dayDelta = localCalendarOrdinal(date) - localCalendarOrdinal(new Date());
  if (dayDelta === 0) return 'Today';
  return dayDelta < 0 ? formatPastDistance(Math.abs(dayDelta)) : formatFutureDistance(dayDelta);
}

export function formatPlantEventDate(value?: string | null): string {
  return formatDetailDate(value);
}
