'use client';

import ExcelJS from 'exceljs';
import { formatCurrency, formatNumber } from '@/lib/helper';
import {
  HppPerKandangReport,
  HppPerKandangRow,
  HppPerKandangPerWeightRange,
} from '@/types/api/report/hpp-per-kandang';

interface HppPerKandangExportExcelParams {
  data: HppPerKandangReport;
  allFeedSuppliers: string;
  allDocSuppliers: string;
}

const formatSuppliers = (
  suppliers: { alias?: string; name: string }[] | null
): string => {
  if (!suppliers || suppliers.length === 0) return '';
  return suppliers.map((s) => s.alias || s.name).join(' | ');
};

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

  const workbook = new ExcelJS.Workbook();

  // ===== REKAPITULASI WORKSHEET =====
  const rekapitulasiColumns = [
    { header: 'No', key: 'no', width: 5 },
    { header: 'Rentang BW', key: 'weightRange', width: 15 },
    { header: 'Sisa Butir', key: 'eggPieces', width: 15 },
    { header: 'Sisa Kg', key: 'eggKg', width: 12 },
    { header: 'Rata-Rata Bobot (Kg)', key: 'avgWeight', width: 18 },
    { header: 'Feed (Supplier)', key: 'feedSuppliers', width: 20 },
    { header: 'DOC (Supplier)', key: 'docSuppliers', width: 20 },
    { header: 'Rata-Rata Harga DOC', key: 'avgDocPrice', width: 20 },
    { header: 'HPP Telur (Rp/Kg)', key: 'eggHpp', width: 18 },
    { header: 'Nominal Sisa', key: 'eggValue', width: 25 },
  ];

  const rekapitulasiWorksheet = workbook.addWorksheet('Rekapitulasi');
  rekapitulasiWorksheet.columns = rekapitulasiColumns;

  const perWeightRangeSummary = params.data.summary.per_weight_range || [];

  perWeightRangeSummary.forEach(
    (item: HppPerKandangPerWeightRange, index: number) => {
      rekapitulasiWorksheet.addRow({
        no: index + 1,
        weightRange: item.label || '',
        eggPieces: formatNumber(item.egg_production_pieces || 0),
        eggKg: formatNumber(item.egg_production_kg || 0),
        avgWeight: formatNumber(item.avg_weight_kg || 0),
        feedSuppliers: formatSuppliers(item.feed_suppliers),
        docSuppliers: formatSuppliers(item.doc_suppliers),
        avgDocPrice: formatCurrency(item.average_doc_price_rp || 0),
        eggHpp: formatCurrency(item.egg_hpp_rp_per_kg || 0),
        eggValue: formatCurrency(item.egg_value_rp || 0),
      });
    }
  );

  // ===== DETAIL PER KANDANG WORKSHEET =====
  const detailColumns = [
    { header: 'No', key: 'no', width: 5 },
    { header: 'Kandang', key: 'kandang', width: 30 },
    { header: 'Rentang Bobot', key: 'weightRange', width: 15 },
    { header: 'Rata-Rata Bobot (KG)', key: 'avgWeightKg', width: 18 },
    { header: 'Sisa Telur (Butir)', key: 'eggPieces', width: 15 },
    { header: 'Sisa Telur (KG)', key: 'eggKg', width: 15 },
    { header: 'Feed (Supplier)', key: 'feedSuppliers', width: 20 },
    { header: 'DOC (Supplier)', key: 'docSuppliers', width: 20 },
    { header: 'Rata-Rata Harga DOC (Rp)', key: 'avgDocPrice', width: 20 },
    { header: 'HPP Telur (Rp/Kg)', key: 'eggHpp', width: 18 },
    { header: 'Nilai Nominal Sisa Telur (Rp)', key: 'eggValue', width: 25 },
  ];

  const detailWorksheet = workbook.addWorksheet('Detail Per Kandang');
  detailWorksheet.columns = detailColumns;

  const allExportData = params.data.rows;

  allExportData.forEach((item: HppPerKandangRow, index: number) => {
    detailWorksheet.addRow({
      no: index + 1,
      kandang: item.kandang?.name || '',
      weightRange: item.weight_range
        ? `${formatNumber(item.weight_range.weight_min)} - ${formatNumber(item.weight_range.weight_max)}`
        : '',
      avgWeightKg: formatNumber(item.avg_weight_kg || 0),
      eggPieces: formatNumber(item.egg_production_pieces || 0),
      eggKg: formatNumber(item.egg_production_kg || 0),
      feedSuppliers: formatSuppliers(item.feed_suppliers),
      docSuppliers: formatSuppliers(item.doc_suppliers),
      avgDocPrice: formatCurrency(item.average_doc_price_rp || 0),
      eggHpp: formatCurrency(item.egg_hpp_rp_per_kg || 0),
      eggValue: formatCurrency(item.egg_value_rp || 0),
    });
  });

  // Add TOTAL row
  const summaryTotal = params.data.summary.total;
  detailWorksheet.addRow({
    no: 'TOTAL',
    kandang: 'ALL',
    weightRange: '-',
    avgWeightKg: formatNumber(summaryTotal?.average_weight_kg || 0),
    eggPieces: formatNumber(summaryTotal?.total_egg_production_pieces || 0),
    eggKg: formatNumber(summaryTotal?.total_egg_production_kg || 0),
    feedSuppliers: params.allFeedSuppliers,
    docSuppliers: params.allDocSuppliers,
    avgDocPrice: formatCurrency(summaryTotal?.total_average_doc_price_rp || 0),
    eggHpp: formatCurrency(summaryTotal?.average_egg_hpp_rp_per_kg || 0),
    eggValue: formatCurrency(summaryTotal?.total_egg_value_rp || 0),
  });

  const filename = `laporan-hpp-harian-kandang-periode-${params.data.period}.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);
};
