import type { BadgeVariant } from '@/components/ui/shared/Badge';
import { formatAppDate, APP_DATE } from '@/lib/i18n/format';

export function toDateInputValue(iso: string | null | undefined): string {
  if (!iso) return '';
  const date = new Date(iso);
  if (Number.isNaN(date.getTime())) return '';
  return date.toISOString().slice(0, 10);
}

export function startOfUtcDay(date = new Date()): Date {
  const d = new Date(date);
  d.setUTCHours(0, 0, 0, 0);
  return d;
}

export function formatLabCaseDueDate(
  iso: string | null | undefined,
  locale: string,
): string | null {
  if (!iso) return null;
  return formatAppDate(iso, locale, APP_DATE.short);
}

/** Whole calendar days from today (UTC) until due date. Negative = overdue. */
export function daysUntilDue(iso: string | null | undefined): number | null {
  if (!iso) return null;
  const due = new Date(iso);
  if (Number.isNaN(due.getTime())) return null;
  const msPerDay = 24 * 60 * 60 * 1000;
  return Math.round((startOfUtcDay(due).getTime() - startOfUtcDay().getTime()) / msPerDay);
}

/** Green: >7 days · Yellow: 2–7 days · Red: ≤1 day (today, tomorrow, or overdue). */
export function dueDateBadgeVariantFromIso(iso: string | null | undefined): BadgeVariant {
  const days = daysUntilDue(iso);
  if (days === null) return 'default';
  if (days <= 1) return 'danger';
  if (days <= 7) return 'warning';
  return 'success';
}
