/** Format Frappe datetime for `<input type="datetime-local" />`. */
export function formatDatetimeForInput(dateStr: string | null | undefined): string {
  if (!dateStr) return '';
  return dateStr.replace(' ', 'T').slice(0, 16);
}

/** Convert datetime-local value to Frappe datetime string. */
export function formatDatetimeForApi(value: string | null | undefined): string {
  if (!value) return '';
  if (value.includes('T')) {
    const [date, time] = value.split('T');
    if (!time) return date;
    return `${date} ${time.length === 5 ? `${time}:00` : time}`;
  }
  return value;
}

export function nowDatetimeLocal(): string {
  const d = new Date();
  const pad = (n: number) => String(n).padStart(2, '0');
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
}

export function calculateTotalHoursSpent(
  firstRespondedOn?: string | null,
  completionDate?: string | null
): number {
  if (!firstRespondedOn || !completionDate) return 0;

  const start = new Date(formatDatetimeForApi(firstRespondedOn).replace(' ', 'T'));
  const end = new Date(formatDatetimeForApi(completionDate).replace(' ', 'T'));

  if (Number.isNaN(start.getTime()) || Number.isNaN(end.getTime()) || end < start) {
    return 0;
  }

  return Math.round(((end.getTime() - start.getTime()) / (1000 * 3600)) * 100) / 100;
}

export function applyWorkOrderStatusTimestamps<T extends {
  repair_status?: string;
  first_responded_on?: string;
  completion_date?: string;
  total_hours_spent?: number;
}>(data: T): T {
  const next = { ...data };
  const now = nowDatetimeLocal();

  if (next.repair_status === 'Work In Progress' && !next.first_responded_on) {
    next.first_responded_on = now;
  }

  if (next.repair_status === 'Completed' && !next.completion_date) {
    next.completion_date = now;
  }

  next.total_hours_spent = calculateTotalHoursSpent(
    next.first_responded_on,
    next.completion_date
  );

  return next;
}
