'use client';

import ExcelJS from 'exceljs';
import {
  formatCurrency,
  formatNumber,
  formatDate,
  formatVechicleNumber,
} from '@/lib/helper';
import { DailyMarketingRow, SalesSummary } from '@/types/api/report/marketing';

interface DailyMarketingExportExcelParams {
  data: DailyMarketingRow[];
  summaryTotal?: SalesSummary;
  period?: string;
}

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

  const workbook = new ExcelJS.Workbook();

  // ===== DAILY MARKETING WORKSHEET =====
  const columns = [
    { header: 'No', key: 'no', width: 5 },
    { header: 'Tanggal Jual', key: 'soDate', width: 15 },
    { header: 'Tanggal Realisasi', key: 'realizationDate', width: 18 },
    { header: 'Aging', key: 'aging', width: 10 },
    { header: 'Gudang Fisik', key: 'warehouse', width: 25 },
    { header: 'Pelanggan', key: 'customer', width: 25 },
    { header: 'No. DO', key: 'doNumber', width: 15 },
    { header: 'Sales/Marketing', key: 'sales', width: 20 },
    { header: 'No. Polisi', key: 'vehicleNumber', width: 15 },
    { header: 'Marketing Type', key: 'marketingType', width: 15 },
    { header: 'Produk', key: 'product', width: 20 },
    { header: 'Kuantitas', key: 'qty', width: 12 },
    { header: 'Bobot Rata-Rata (Kg)', key: 'averageWeight', width: 20 },
    { header: 'Bobot Total (Kg)', key: 'totalWeight', width: 18 },
    { header: 'Harga Jual (Rp)', key: 'salesPrice', width: 18 },
    { header: 'HPP (Rp)', key: 'hppPrice', width: 15 },
    { header: 'HPP Amount (Rp)', key: 'hppAmount', width: 20 },
    { header: 'Total (Rp)', key: 'salesAmount', width: 20 },
  ];

  const worksheet = workbook.addWorksheet('Laporan Marketing Harian');
  worksheet.columns = columns;

  // Add data rows
  params.data.forEach((item: DailyMarketingRow, index: number) => {
    worksheet.addRow({
      no: index + 1,
      soDate: formatDate(item.so_date, 'DD-MMM-YYYY'),
      realizationDate: formatDate(item.realization_date, 'DD-MMM-YYYY'),
      aging: `${item.aging_days} hari`,
      warehouse: item.warehouse?.name || '',
      customer: item.customer?.name || '',
      doNumber: item.do_number || '',
      sales: item.sales?.name || '',
      vehicleNumber: formatVechicleNumber(item.vehicle_number),
      marketingType: item.marketing_type || '',
      product: item.product?.name || '',
      qty: formatNumber(item.qty || 0),
      averageWeight: formatNumber(item.average_weight_kg || 0),
      totalWeight: formatNumber(item.total_weight_kg || 0),
      salesPrice: formatCurrency(item.sales_price_per_kg || 0),
      hppPrice: formatCurrency(item.hpp_price_per_kg || 0),
      hppAmount: formatCurrency(item.hpp_amount || 0),
      salesAmount: formatCurrency(item.sales_amount || 0),
    });
  });

  // Add TOTAL row if summary data is available
  if (params.summaryTotal) {
    worksheet.addRow({
      no: 'TOTAL',
      soDate: '',
      realizationDate: '',
      aging: '',
      warehouse: '',
      customer: '',
      doNumber: '',
      sales: '',
      vehicleNumber: '',
      marketingType: '',
      product: '',
      qty: formatNumber(params.summaryTotal.total_qty || 0),
      averageWeight: formatNumber(params.summaryTotal.average_weight_kg || 0),
      totalWeight: formatNumber(params.summaryTotal.total_weight_kg || 0),
      salesPrice: formatCurrency(params.summaryTotal.average_sales_price || 0),
      hppPrice: formatCurrency(params.summaryTotal.total_hpp_price_per_kg || 0),
      hppAmount: formatCurrency(params.summaryTotal.total_hpp_amount || 0),
      salesAmount: formatCurrency(params.summaryTotal.total_sales_amount || 0),
    });
  }

  worksheet.columns.forEach((column: { width?: number }) => {
    if (column.width && column.width < 10) {
      column.width = 10;
    }
  });

  const currentDate = new Date().toISOString().split('T')[0];
  const filename = params.period
    ? `laporan-marketing-harian-${params.period}.xlsx`
    : `laporan-marketing-harian-${currentDate}.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);
};
