'use client';

import * as XLSX from 'xlsx';
import type { Uniformity } from '@/types/api/production/uniformity';
import { formatDate, formatNumber } from '@/lib/helper';

interface UniformityExportExcelParams {
  data: Uniformity[];
  params: {
    location_name?: string;
    project_flock_name?: string;
    kandang_name?: string;
    start_date?: string;
    end_date?: string;
  };
}

const getStatusText = (status: string) => {
  switch (status) {
    case 'APPROVED':
      return 'Disetujui';
    case 'REJECTED':
      return 'Ditolak';
    case 'CREATED':
      return 'Pengajuan';
    default:
      return status;
  }
};

export const generateUniformityExcel = (
  data: UniformityExportExcelParams['data'],
  params: UniformityExportExcelParams['params']
): void => {
  if (!data || data.length === 0) {
    return;
  }

  const excelData: { [key: string]: string | number }[] = data.map(
    (item: Uniformity, index: number) => ({
      No: index + 1,
      Lokasi: item.location_name || '',
      'Project Flock': item.flock_name || '',
      Kandang: item.kandang_name || '',
      Tanggal: formatDate(item.applied_at, 'DD MMM YYYY'),
      Minggu: item.week || 0,
      Status: getStatusText(item.status),
      'Uniformity (%)': formatNumber(item.uniformity),
      'CV (%)': formatNumber(item.cv),
      'Chick Qty': formatNumber(item.chick_qty_of_weight),
      'Uniform Qty': formatNumber(item.uniform_qty),
      'Mean Up': formatNumber(item.mean_up),
      'Mean Down': formatNumber(item.mean_down),
    })
  );

  const worksheet = XLSX.utils.json_to_sheet(excelData);

  const colWidths = [
    { wch: 6 }, // No
    { wch: 25 }, // Lokasi
    { wch: 20 }, // Project Flock
    { wch: 15 }, // Kandang
    { wch: 15 }, // Tanggal
    { wch: 10 }, // Minggu
    { wch: 12 }, // Status
    { wch: 15 }, // Uniformity (%)
    { wch: 10 }, // CV (%)
    { wch: 12 }, // Chick Qty
    { wch: 12 }, // Uniform Qty
    { wch: 12 }, // Mean Up
    { wch: 12 }, // Mean Down
  ];
  worksheet['!cols'] = colWidths;

  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Uniformity');

  const period =
    params.start_date && params.end_date
      ? `${params.start_date}-${params.end_date}`
      : formatDate(new Date(), 'YYYY-MM-DD');
  const filename = `laporan-uniformity-${period}.xlsx`;

  XLSX.writeFile(workbook, filename);
};
