import {generateCsvBlob} from './csvExport';
import {generateExcelBlob} from './excelExport';
import {generatePdfBlob} from './pdfExport';

export type ExportFormat = 'pdf' | 'excel' | 'csv';

export interface ExportColumn {
  key: string;
  header: string;
}

export interface ExportDataParams {
  filename: string;
  title: string;
  subtitle?: string;
  columns: ExportColumn[];
  data: Record<string, any>[];
  format: ExportFormat;
}

function triggerBrowserDownload(blob: Blob, filename: string): void {
  console.log('[exportManager] Blob generated successfully:', {
    size: blob.size,
    type: blob.type,
    isBlob: blob instanceof Blob,
  });
  console.log('[exportManager] Triggering download link for:', filename);

  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.download = filename;
  document.body.appendChild(link);

  console.log('[exportManager] Executing link.click()...');
  link.click();
  document.body.removeChild(link);

  setTimeout(() => URL.revokeObjectURL(url), 1000);
}

export async function exportData({
  filename,
  title,
  subtitle,
  columns,
  data,
  format,
}: ExportDataParams): Promise<void> {
  console.log('[exportData] Starting generation for format:', format, {filename, title});

  // Artificial generation delay for smooth UX transition
  await new Promise((res) => setTimeout(res, 450));

  const dateTag = new Date().toISOString().slice(0, 10);
  let blob: Blob;
  let finalFilename = filename;

  switch (format) {
    case 'pdf':
      blob = generatePdfBlob(title, subtitle, columns, data);
      if (!finalFilename.endsWith('.pdf')) finalFilename = `${finalFilename}_${dateTag}.pdf`;
      break;

    case 'excel':
      blob = generateExcelBlob(title, columns, data);
      if (!finalFilename.endsWith('.xlsx')) finalFilename = `${finalFilename}_${dateTag}.xlsx`;
      break;

    case 'csv':
      blob = generateCsvBlob(columns, data);
      if (!finalFilename.endsWith('.csv')) finalFilename = `${finalFilename}_${dateTag}.csv`;
      break;
  }

  triggerBrowserDownload(blob, finalFilename);
}
