/**
 * Patient and Order utility functions for LIS
 * @module $lib/utils/patients
 */

/**
 * Format patient name from components
 * @param {Object} patient - Patient object
 * @param {string} [patient.Prefix] - Name prefix
 * @param {string} [patient.NameFirst] - First name
 * @param {string} [patient.NameMiddle] - Middle name
 * @param {string} [patient.NameLast] - Last name
 * @param {string} [patient.FullName] - Pre-formatted full name
 * @returns {string} Formatted full name
 */
export function formatPatientName(patient) {
  if (!patient) return '-';
  if (patient.FullName) return patient.FullName;
  return [
    patient.Prefix,
    patient.NameFirst,
    patient.NameMiddle,
    patient.NameLast
  ].filter(Boolean).join(' ') || '-';
}

/**
 * Format sex display
 * @param {Object} patient - Patient object
 * @param {string} [patient.SexLabel] - Sex label
 * @param {string} [patient.Sex] - Sex code (1=Female, 2=Male)
 * @returns {string} Formatted sex
 */
export function formatSex(patient) {
  if (!patient) return '-';
  if (patient.SexLabel) return patient.SexLabel;
  if (patient.Sex === '1') return 'Female';
  if (patient.Sex === '2') return 'Male';
  return '-';
}

/**
 * Format date for display
 * @param {string} dateStr - ISO date string
 * @returns {string} Formatted date
 */
export function formatDate(dateStr) {
  if (!dateStr) return '-';
  try {
    return new Date(dateStr).toLocaleDateString();
  } catch {
    return '-';
  }
}

/**
 * Format datetime for display
 * @param {string} dateStr - ISO datetime string
 * @returns {string} Formatted datetime
 */
export function formatDateTime(dateStr) {
  if (!dateStr) return '-';
  try {
    return new Date(dateStr).toLocaleString();
  } catch {
    return '-';
  }
}

/**
 * Format birthdate for patient list
 * @param {Object} patient - Patient object
 * @param {string} [patient.Birthdate] - Birthdate
 * @param {string} [patient.BirthdateFormatted] - Pre-formatted birthdate
 * @returns {string} Formatted birthdate
 */
export function formatBirthdate(patient) {
  if (!patient) return '-';
  if (patient.BirthdateFormatted) return patient.BirthdateFormatted;
  return formatDate(patient.Birthdate);
}

/**
 * Calculate age from birthdate
 * @param {string} birthdate - Birthdate string
 * @returns {string} Age in years
 */
export function calculateAge(birthdate) {
  if (!birthdate) return '-';
  try {
    const birth = new Date(birthdate);
    const today = new Date();
    let age = today.getFullYear() - birth.getFullYear();
    const monthDiff = today.getMonth() - birth.getMonth();
    if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) {
      age--;
    }
    return `${age}y`;
  } catch {
    return '-';
  }
}

/**
 * Get order status badge class
 * @param {string} status - Order status
 * @returns {string} DaisyUI badge class
 */
export function getOrderStatusClass(status) {
  const statusMap = {
    'pending': 'badge-warning',
    'in_progress': 'badge-info',
    'completed': 'badge-success',
    'cancelled': 'badge-error',
    'collected': 'badge-primary',
    'verified': 'badge-accent',
  };
  return statusMap[status?.toLowerCase()] || 'badge-ghost';
}

/**
 * Format order number
 * @param {Object} order - Order object
 * @param {string} [order.OrderNumber] - Order number
 * @param {string} [order.OrderID] - Order ID
 * @returns {string} Formatted order number
 */
export function formatOrderNumber(order) {
  if (!order) return '-';
  return order.OrderNumber || order.OrderID || '-';
}

/**
 * Debounce function for search inputs
 * @param {Function} func - Function to debounce
 * @param {number} wait - Milliseconds to wait
 * @returns {Function} Debounced function
 */
export function debounce(func, wait = 300) {
  let timeout;
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout);
      func(...args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
}
