'use client';

import ExcelJS from 'exceljs';
import { formatDate, formatCurrency, formatNumber } from '@/lib/helper';
import { LogisticPurchasePerSupplierReport } from '@/types/api/report/logistic-stock';

interface PurchasesPerSupplierExportExcelParams {
  data: LogisticPurchasePerSupplierReport[];
}

export const generatePurchasesPerSupplierExcel = async (
  params: PurchasesPerSupplierExportExcelParams
): Promise<void> => {
  if (!params.data || params.data.length === 0) {
    return;
  }

  const workbook = new ExcelJS.Workbook();

  const columns = [
    { header: 'No', key: 'no', width: 5 },
    { header: 'Tanggal Terima', key: 'receiveDate', width: 15 },
    { header: 'Tanggal PO', key: 'poDate', width: 15 },
    { header: 'No. Referensi', key: 'poNumber', width: 15 },
    { header: 'Nama Produk', key: 'productName', width: 30 },
    { header: 'Tujuan', key: 'warehouse', width: 20 },
    { header: 'QTY', key: 'qty', width: 10 },
    { header: 'Harga Beli (Rp)', key: 'unitPrice', width: 18 },
    { header: 'Value Harga Beli (Rp)', key: 'purchaseValue', width: 20 },
    { header: 'Transport (Rp)', key: 'transportUnitPrice', width: 15 },
    { header: 'Value Transport (Rp)', key: 'transportValue', width: 20 },
    { header: 'Jumlah (Rp)', key: 'totalAmount', width: 18 },
    { header: 'Ekspedisi', key: 'expedition', width: 15 },
    { header: 'Surat Jalan', key: 'deliveryNumber', width: 15 },
  ];

  for (const supplierReport of params.data) {
    const supplierData = supplierReport.rows;
    const supplierName = supplierReport.supplier?.name || 'Unknown Supplier';

    const worksheet = workbook.addWorksheet(supplierName.substring(0, 31));
    worksheet.columns = columns;

    supplierData.forEach((item, index) => {
      worksheet.addRow({
        no: index + 1,
        receiveDate: item.receive_date
          ? formatDate(item.receive_date, 'DD MMM YYYY')
          : '',
        poDate: item.po_date ? formatDate(item.po_date, 'DD MMM YYYY') : '',
        poNumber: item.po_number || '',
        productName: item.product?.name || '',
        warehouse: item.warehouse?.name || '',
        qty: formatNumber(item.qty || 0),
        unitPrice: formatCurrency(item.unit_price || 0),
        purchaseValue: formatCurrency(item.purchase_value || 0),
        transportUnitPrice: formatCurrency(item.transport_unit_price || 0),
        transportValue: formatCurrency(item.transport_value || 0),
        totalAmount: formatCurrency(item.total_amount || 0),
        expedition: item.expedition || '',
        deliveryNumber: item.delivery_number || '',
      });
    });

    if (supplierReport.summary) {
      worksheet.addRow({
        no: 'Total',
        receiveDate: '',
        poDate: '',
        poNumber: '',
        productName: '',
        warehouse: '',
        qty: formatNumber(supplierReport.summary.total_qty || 0),
        unitPrice: '',
        purchaseValue: formatCurrency(
          supplierReport.summary.total_purchase_value || 0
        ),
        transportUnitPrice: '',
        transportValue: formatCurrency(
          supplierReport.summary.total_transport_value || 0
        ),
        totalAmount: formatCurrency(supplierReport.summary.total_amount || 0),
        expedition: '',
        deliveryNumber: '',
      });
    }
  }

  const filename = `laporan-pembelian-per-supplier-dicetak-pada-${formatDate(new Date(), 'YYYY-MM-DD-HHmm')}.xlsx`;

  const buffer = await workbook.xlsx.writeBuffer();
  const blob = new Blob([buffer], {
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  });
  const url = window.URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.download = filename;
  link.click();
  window.URL.revokeObjectURL(url);
};
