import ExcelJS from "exceljs";

export const generateCustomerReceiptExcel = async (receipts: any[]) => {
  const workbook = new ExcelJS.Workbook();
  const sheet = workbook.addWorksheet("Customer Receipts");

  sheet.columns = [
    { header: "S.No.", key: "serialNo", width: 10 },
    { header: "Receipt Date", key: "receiptDate", width: 18 },
    { header: "Customer", key: "customerName", width: 28 },
    { header: "Amount", key: "amount", width: 15 },
    { header: "Payment Mode", key: "paymentMode", width: 18 },
    { header: "Reference No", key: "referenceNo", width: 25 },
    { header: "Remarks", key: "remarks", width: 35 },
  ];

  const headerRow = sheet.getRow(1);
  headerRow.font = {
    bold: true,
    color: { argb: "FFFFFFFF" },
  };
  headerRow.fill = {
    type: "pattern",
    pattern: "solid",
    fgColor: { argb: "FF4F81BD" },
  };
  headerRow.alignment = {
    horizontal: "center",
    vertical: "middle",
  };

  receipts.forEach((receipt, index) => {
    sheet.addRow({
      serialNo: index + 1,
      receiptDate: new Date(receipt.receiptDate).toLocaleDateString("en-GB").replace(/\//g, "-"),
      customerName: receipt.customer?.name ?? "",
      amount: Number(receipt.amount),
      paymentMode: receipt.paymentMode,
      referenceNo: receipt.referenceNo ?? "",
      remarks: receipt.remarks ?? "",
    });
  });

  const totalAmount = receipts.reduce(
    (sum, receipt) => sum + Number(receipt.amount),
    0
  );

  const totalRow = sheet.addRow({
    customerName: "Total",
    amount: totalAmount,
  });
  totalRow.font = { bold: true };

  sheet.eachRow((row) => {
    row.eachCell((cell) => {
      cell.border = {
        top: { style: "thin" },
        left: { style: "thin" },
        bottom: { style: "thin" },
        right: { style: "thin" },
      };
    });
  });

  sheet.getColumn("amount").numFmt = "#,##0.00";

  return workbook;
};
