import dayjs from 'dayjs';

export type EventRuntimeStatus = 'pending' | 'in_progress' | 'completed';

export type EventStatusDisplay = {
  key: EventRuntimeStatus;
  label: 'Upcoming' | 'Active' | 'Past';
  color: 'warning' | 'info' | 'default';
};

/**
 * Time-based event status shared by list, calendar, modal, and dashboard KPIs.
 * Upcoming = not started | Active = started & not ended | Past = ended
 */
export function calculateEventRuntimeStatus(
  startTime?: string | Date | null,
  endTime?: string | Date | null
): EventRuntimeStatus {
  if (!startTime) return 'pending';

  const now = dayjs();
  const start = dayjs(startTime);
  let end = endTime ? dayjs(endTime) : start.endOf('day');

  if (!start.isValid()) return 'pending';

  if (!end.isValid() || !endTime || end.isBefore(start) || end.isSame(start)) {
    end = start.endOf('day');
  }

  if (now.isBefore(start)) return 'pending';
  if (now.isAfter(end)) return 'completed';
  return 'in_progress';
}

export function getEventStatusDisplay(
  startTime?: string | Date | null,
  endTime?: string | Date | null
): EventStatusDisplay {
  const key = calculateEventRuntimeStatus(startTime, endTime);
  switch (key) {
    case 'pending':
      return { key, label: 'Upcoming', color: 'warning' };
    case 'in_progress':
      return { key, label: 'Active', color: 'info' };
    case 'completed':
    default:
      return { key: 'completed', label: 'Past', color: 'default' };
  }
}
