import ExcelJS from 'exceljs';

export async function generateExcelReport(
  title: string,
  headers: string[],
  rows: string[][]
): Promise<Buffer> {
  const workbook = new ExcelJS.Workbook();
  workbook.creator = 'ISPM ERP';
  workbook.created = new Date();

  const worksheet = workbook.addWorksheet(title);

  // Title row
  worksheet.mergeCells(1, 1, 1, headers.length);
  const titleCell = worksheet.getCell('A1');
  titleCell.value = `ISPM - ${title}`;
  titleCell.font = { size: 14, bold: true };
  titleCell.alignment = { horizontal: 'center' };

  // Date row
  worksheet.mergeCells(2, 1, 2, headers.length);
  const dateCell = worksheet.getCell('A2');
  dateCell.value = `Genere le ${new Date().toLocaleDateString('fr-FR')}`;
  dateCell.font = { size: 9, italic: true };
  dateCell.alignment = { horizontal: 'center' };

  // Empty row
  worksheet.addRow([]);

  // Headers
  const headerRow = worksheet.addRow(headers);
  headerRow.eachCell((cell) => {
    cell.font = { bold: true, color: { argb: 'FFFFFFFF' } };
    cell.fill = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: 'FF2563EB' },
    };
    cell.alignment = { horizontal: 'center', vertical: 'middle' };
    cell.border = {
      top: { style: 'thin' },
      left: { style: 'thin' },
      bottom: { style: 'thin' },
      right: { style: 'thin' },
    };
  });

  // Data rows
  rows.forEach((row, index) => {
    const dataRow = worksheet.addRow(row);
    dataRow.eachCell((cell) => {
      cell.border = {
        top: { style: 'thin' },
        left: { style: 'thin' },
        bottom: { style: 'thin' },
        right: { style: 'thin' },
      };
      if (index % 2 === 0) {
        cell.fill = {
          type: 'pattern',
          pattern: 'solid',
          fgColor: { argb: 'FFF3F4F6' },
        };
      }
    });
  });

  // Auto-fit columns
  worksheet.columns.forEach((column) => {
    let maxLength = 0;
    column.eachCell?.({ includeEmpty: true }, (cell) => {
      const cellLength = cell.value ? cell.value.toString().length : 10;
      if (cellLength > maxLength) maxLength = cellLength;
    });
    column.width = Math.min(Math.max(maxLength + 2, 10), 40);
  });

  const buffer = await workbook.xlsx.writeBuffer();
  return Buffer.from(buffer);
}
