import * as XLSX from 'xlsx';
import { ReportExpense } from '@/types/api/report/report-expense';
import { formatDate } from '@/lib/helper';

export const generateReportExpenseExcel = async (
  data: ReportExpense[]
): Promise<void> => {
  // Group by supplier
  const groupedBySupplier: Record<string, ReportExpense[]> = {};
  data.forEach((item) => {
    const supplierName = item.supplier?.name || 'Unknown Supplier';
    if (!groupedBySupplier[supplierName]) {
      groupedBySupplier[supplierName] = [];
    }
    groupedBySupplier[supplierName].push(item);
  });

  const workbook = XLSX.utils.book_new();

  Object.entries(groupedBySupplier).forEach(([supplierName, supplierData]) => {
    const totals = supplierData.reduce(
      (acc, item) => ({
        qty_pengajuan: acc.qty_pengajuan + (item.pengajuan?.qty || 0),
        total_pengajuan:
          acc.total_pengajuan +
          (item.pengajuan?.qty || 0) * (item.pengajuan?.price || 0),
        qty_realisasi: acc.qty_realisasi + (item.realisasi?.qty || 0),
        total_realisasi:
          acc.total_realisasi +
          (item.realisasi?.qty || 0) * (item.realisasi?.price || 0),
      }),
      {
        qty_pengajuan: 0,
        total_pengajuan: 0,
        qty_realisasi: 0,
        total_realisasi: 0,
      }
    );

    const excelData = supplierData.map((item, index) => ({
      No: index + 1,
      'No. PO': item.po_number || '',
      'No. Referensi': item.reference_number || '',
      'Tanggal Realisasi': item.realization_date
        ? formatDate(item.realization_date, 'DD MMM YYYY')
        : '',
      'Tanggal Transaksi': item.transaction_date
        ? formatDate(item.transaction_date, 'DD MMM YYYY')
        : '',
      Kategori: item.category || '',
      Produk: item.pengajuan?.nonstock?.name || '',
      Lokasi: item.kandang?.location?.name || '',
      Kandang: item.kandang?.name || '',
      'Qty Pengajuan': item.pengajuan?.qty || 0,
      'Harga Pengajuan': item.pengajuan?.price || 0,
      'Total Pengajuan':
        (item.pengajuan?.qty || 0) * (item.pengajuan?.price || 0),
      'Qty Realisasi': item.realisasi?.qty || 0,
      'Harga Realisasi': item.realisasi?.price || 0,
      'Total Realisasi':
        (item.realisasi?.qty || 0) * (item.realisasi?.price || 0),
      'Status Pencairan': item.latest_approval?.step_name || '',
    }));

    excelData.push({
      No: 'Total' as unknown as number,
      'No. PO': '',
      'No. Referensi': '',
      'Tanggal Realisasi': '',
      'Tanggal Transaksi': '',
      Kategori: '',
      Produk: '',
      Lokasi: '',
      Kandang: '',
      'Qty Pengajuan': totals.qty_pengajuan,
      'Harga Pengajuan': 0,
      'Total Pengajuan': totals.total_pengajuan,
      'Qty Realisasi': totals.qty_realisasi,
      'Harga Realisasi': 0,
      'Total Realisasi': totals.total_realisasi,
      'Status Pencairan': '',
    });

    const worksheet = XLSX.utils.json_to_sheet(excelData);
    const colWidths = [
      { wch: 5 },
      { wch: 20 },
      { wch: 20 },
      { wch: 15 },
      { wch: 15 },
      { wch: 15 },
      { wch: 30 },
      { wch: 20 },
      { wch: 15 },
      { wch: 15 },
      { wch: 15 },
      { wch: 20 },
      { wch: 15 },
      { wch: 20 },
    ];
    worksheet['!cols'] = colWidths;

    const sheetName = supplierName.slice(0, 31);
    XLSX.utils.book_append_sheet(workbook, worksheet, sheetName);
  });

  const filename = `Laporan-BOP-${formatDate(new Date(), 'YYYY-MM-DD-HHmm')}.xlsx`;
  XLSX.writeFile(workbook, filename);
};
