type ListColumn = { key: string; label?: string; type?: string };

export function ucwords(value: unknown): string {
  if (value === null || value === undefined || value === '') return '';

  return String(value)
    .trim()
    .replace(/[_-]+/g, ' ')
    .replace(/\b\w/g, (char) => char.toUpperCase());
}

function formatColumnValue(row: Record<string, unknown>, column: ListColumn): string {
  const value = row[column.key];

  if (value === null || value === undefined || value === '') {
    return '';
  }

  if (column.type === 'badge') {
    return ucwords(value);
  }

  if (column.key === 'price' || column.key === 'cost_price') {
    const amount = Number(value);
    return Number.isFinite(amount) ? amount.toFixed(2) : String(value);
  }

  if (column.key === 'quantity_on_hand') {
    if (String(row.type || '').toLowerCase() === 'service') {
      return '';
    }
    const qty = Number(value);
    return Number.isFinite(qty) ? String(qty) : String(value);
  }

  if (column.key === 'duration_minutes') {
    const minutes = Number(value);
    if (!minutes) return '';
    return minutes === 60 ? '1 hour' : `${minutes} min`;
  }

  return String(value);
}

export function buildRecordPresentation(
  resource: string,
  row: Record<string, unknown>,
  columns: ListColumn[] = [],
): { title: string; subtitle: string; badge?: string; lowStock?: boolean } {
  if (resource === 'services') {
    const title = String(row.name || `#${row.id}`);
    const badge = row.type ? ucwords(row.type) : undefined;
    const subtitleParts = [
      row.assigned_staff && String(row.assigned_staff) !== '-' ? String(row.assigned_staff) : null,
      row.sku ? `SKU ${row.sku}` : null,
      row.price !== null && row.price !== undefined && row.price !== ''
        ? `Price ${Number(row.price).toFixed(2)}`
        : null,
      String(row.type || '').toLowerCase() === 'product' && row.quantity_on_hand !== undefined
        ? `Qty ${row.quantity_on_hand}`
        : null,
      row.duration_minutes && Number(row.duration_minutes) > 0
        ? `${row.duration_minutes} min`
        : null,
    ].filter(Boolean);

    if (row.low_stock) {
      subtitleParts.unshift('Low stock');
    }

    return {
      title,
      badge,
      subtitle: subtitleParts.join(' · '),
      lowStock: Boolean(row.low_stock),
    };
  }

  const titleCols = columns.slice(0, 2);
  const subtitleCols = columns.slice(2, 5);
  const badgeCol = columns.find((column) => column.type === 'badge');

  const title = titleCols
    .filter((column) => column.type !== 'badge')
    .map((column) => formatColumnValue(row, column))
    .filter(Boolean)
    .join(' · ') || `#${row.id}`;

  const badge = badgeCol ? formatColumnValue(row, badgeCol) : undefined;

  const subtitle = subtitleCols
    .filter((column) => column.type !== 'badge')
    .map((column) => formatColumnValue(row, column))
    .filter(Boolean)
    .join(' · ');

  return { title, subtitle, badge: badge || undefined, lowStock: false };
}
