import * as XLSX from 'xlsx';
import { saveAs } from 'file-saver';

interface ExcelColumn {
  header: string;
  key: string;
  width?: number;
}

export function exportToExcel(
  data: Record<string, any>[],
  columns: ExcelColumn[],
  filename: string,
) {
  const rows = data.map((row) =>
    Object.fromEntries(columns.map((col) => [col.header, row[col.key] ?? '']))
  );

  const ws = XLSX.utils.json_to_sheet(rows);

  // Aplicar anchos de columna
  ws['!cols'] = columns.map((col) => ({ wch: col.width || 15 }));

  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, 'Datos');

  const buf = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
  const blob = new Blob([buf], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
  saveAs(blob, `${filename}.xlsx`);
}
