import ExcelJS from "exceljs";

export const generateSupplierPaymentExcel = async (payments: any[]) => {
  const workbook = new ExcelJS.Workbook();
  const sheet = workbook.addWorksheet("Supplier Payments");

  sheet.columns = [
    { header: "S.No.", key: "serialNo", width: 10 },
    { header: "Payment Date", key: "paymentDate", width: 18 },
    { header: "Supplier", key: "supplierName", 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",
  };

  payments.forEach((payment, index) => {
    sheet.addRow({
      serialNo: index + 1,
      paymentDate: new Date(payment.paymentDate).toLocaleDateString("en-GB").replace(/\//g, "-"),
      supplierName: payment.supplier?.name ?? "",
      amount: Number(payment.amount),
      paymentMode: payment.paymentMode,
      referenceNo: payment.referenceNo ?? "",
      remarks: payment.remarks ?? "",
    });
  });

  const totalAmount = payments.reduce(
    (sum, payment) => sum + Number(payment.amount),
    0
  );

  const totalRow = sheet.addRow({
    supplierName: "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;
};
