'use client';

import ExcelJS from 'exceljs';
import { formatDate, formatCurrency, formatNumber } from '@/lib/helper';
import { CustomerPaymentReport } from '@/types/api/report/customer-payment';

interface CustomerPaymentExportExcelParams {
  data: CustomerPaymentReport[];
}

export const generateCustomerPaymentExcel = async (
  params: CustomerPaymentExportExcelParams
): 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 DO/Bayar', key: 'transDate', width: 15 },
    { header: 'Tanggal Realisasi', key: 'deliveryDate', width: 15 },
    { header: 'Aging', key: 'aging', width: 8 },
    { header: 'Referensi', key: 'reference', width: 12 },
    { header: 'Nomor Polisi', key: 'vehicleNumbers', width: 15 },
    { header: 'Ekor/Qty', key: 'qty', width: 10 },
    { header: 'Berat (Kg)', key: 'weight', width: 12 },
    { header: 'AVG', key: 'avgWeight', width: 10 },
    { header: 'Harga/Unit (Rp)', key: 'unitPrice', width: 15 },
    { header: 'Harga Akhir (Rp)', key: 'finalPrice', width: 15 },
    { header: 'Total (Rp)', key: 'totalPrice', width: 15 },
    { header: 'Pembayaran (Rp)', key: 'paymentAmount', width: 15 },
    { header: 'Saldo Piutang (Rp)', key: 'accountsReceivable', width: 15 },
    { header: 'Keterangan', key: 'status', width: 20 },
    { header: 'Pengambilan', key: 'pickupInfo', width: 15 },
    { header: 'Sales/Marketing', key: 'salesPerson', width: 20 },
  ];

  for (const customerReport of params.data) {
    const customerData = customerReport.rows;
    const customerName = customerReport.customer.name || 'Unknown Customer';

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

    const initialRow = worksheet.addRow({
      no: '',
      transDate: '',
      deliveryDate: '',
      aging: '',
      reference: '',
      vehicleNumbers: '',
      qty: '',
      weight: '',
      avgWeight: '',
      unitPrice: '',
      finalPrice: '',
      totalPrice: '',
      paymentAmount: '',
      accountsReceivable: formatCurrency(customerReport.initial_balance || 0),
      status: '',
      pickupInfo: '',
      salesPerson: '',
    });

    const initialBalanceCell = initialRow.getCell('accountsReceivable');
    if (
      typeof customerReport.initial_balance === 'number' &&
      customerReport.initial_balance < 0
    ) {
      initialBalanceCell.font = { color: { argb: 'FFFF0000' } };
    }

    customerData.forEach((item, index) => {
      const row = worksheet.addRow({
        no: index + 1,
        transDate: item.trans_date
          ? formatDate(item.trans_date, 'DD MMM YYYY')
          : '-',
        deliveryDate: item.delivery_date
          ? formatDate(item.delivery_date, 'DD MMM YYYY')
          : '-',
        aging: item.aging_day != null ? formatNumber(item.aging_day) : '-',
        reference: item.reference || '-',
        vehicleNumbers: Array.isArray(item.vehicle_numbers)
          ? item.vehicle_numbers.length > 0
            ? item.vehicle_numbers.join(', ')
            : '-'
          : '-',
        qty: formatNumber(item.qty || 0),
        weight: formatNumber(item.weight || 0),
        avgWeight: formatNumber(item.average_weight || 0),
        unitPrice: formatCurrency(item.unit_price || 0),
        finalPrice: formatCurrency(item.final_price || 0),
        totalPrice: formatCurrency(item.total_price || 0),
        paymentAmount: formatCurrency(item.payment_amount || 0),
        accountsReceivable: formatCurrency(item.accounts_receivable || 0),
        status: item.status || '-',
        pickupInfo: Array.isArray(item.pickup_info)
          ? item.pickup_info.length > 0
            ? item.pickup_info.join(', ')
            : '-'
          : '-',
        salesPerson: item.sales_person || '-',
      });

      const accountsReceivableCell = row.getCell('accountsReceivable');
      if (
        accountsReceivableCell.value &&
        accountsReceivableCell.value.toString().startsWith('-Rp')
      ) {
        accountsReceivableCell.font = { color: { argb: 'FFFF0000' } };
      }
    });

    if (customerReport.summary) {
      const summaryRow = worksheet.addRow({
        no: 'Total',
        transDate: '',
        deliveryDate: '',
        aging: '',
        reference: '',
        vehicleNumbers: '',
        qty: formatNumber(customerReport.summary.total_qty || 0),
        weight: formatNumber(customerReport.summary.total_weight || 0),
        avgWeight: '',
        unitPrice: '',
        finalPrice: formatCurrency(
          customerReport.summary.total_final_amount || 0
        ),
        totalPrice: formatCurrency(
          customerReport.summary.total_grand_amount || 0
        ),
        paymentAmount: formatCurrency(
          customerReport.summary.total_payment || 0
        ),
        accountsReceivable: formatCurrency(
          customerReport.summary.total_accounts_receivable || 0
        ),
        status: '',
        pickupInfo: '',
        salesPerson: '',
      });

      const summaryAccountsReceivableCell =
        summaryRow.getCell('accountsReceivable');
      if (
        summaryAccountsReceivableCell.value &&
        summaryAccountsReceivableCell.value.toString().startsWith('-Rp')
      ) {
        summaryAccountsReceivableCell.font = { color: { argb: 'FFFF0000' } };
      }
    }
  }

  const filename = `laporan-kontrol-pembayaran-customer-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);
};
