
export interface ExportOptions {
  filename: string;
  format: 'csv' | 'xlsx' | 'pdf';
  data: any[];
  columns?: string[];
}

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

export async function exportToCSV(data: any[], filename: string) {
  if (data.length === 0) {
    throw new Error('No data to export');
  }

  const headers = Object.keys(data[0]);
  const csvContent = [
    headers.join(','),
    ...data.map(row =>
      headers.map(header => {
        const value = row[header];
        // Escape commas and quotes
        if (typeof value === 'string' && (value.includes(',') || value.includes('"'))) {
          return `"${value.replace(/"/g, '""')}"`;
        }
        return value;
      }).join(',')
    )
  ].join('\n');

  downloadFile(csvContent, `${filename}.csv`, 'text/csv');
}

export async function exportToJSON(data: any[], filename: string) {
  const jsonContent = JSON.stringify(data, null, 2);
  downloadFile(jsonContent, `${filename}.json`, 'application/json');
}

export async function exportToPDF(data: any[], filename: string, title: string) {
  // This is a placeholder for PDF export
  // In production, you would use a library like jsPDF or pdfmake
  console.log('PDF export not yet implemented');
  
  // For now, export as JSON
  await exportToJSON(data, filename);
}

function downloadFile(content: string, filename: string, mimeType: string) {
  const blob = new Blob([content], { type: mimeType });
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  
  link.href = url;
  link.download = filename;
  document.body.appendChild(link);
  link.click();
  
  document.body.removeChild(link);
  URL.revokeObjectURL(url);
}

// Advanced export with customization
export class ReportExporter {
  private data: any[];
  private filename: string;
  
  constructor(data: any[], filename: string) {
    this.data = data;
    this.filename = filename;
  }
  
  filterColumns(columns: string[]) {
    this.data = this.data.map(row => {
      const filtered: any = {};
      columns.forEach(col => {
        if (col in row) {
          filtered[col] = row[col];
        }
      });
      return filtered;
    });
    return this;
  }
  
  sortBy(column: string, order: 'asc' | 'desc' = 'asc') {
    this.data.sort((a, b) => {
      const aVal = a[column];
      const bVal = b[column];
      
      if (aVal < bVal) return order === 'asc' ? -1 : 1;
      if (aVal > bVal) return order === 'asc' ? 1 : -1;
      return 0;
    });
    return this;
  }
  
  filter(predicate: (row: any) => boolean) {
    this.data = this.data.filter(predicate);
    return this;
  }
  
  async toCSV() {
    await exportToCSV(this.data, this.filename);
  }
  
  async toJSON() {
    await exportToJSON(this.data, this.filename);
  }
  
  async toPDF(title: string) {
    await exportToPDF(this.data, this.filename, title);
  }
}

// Generic export function for use in components
export async function exportData(
  data: any[],
  filename: string,
  format: 'csv' | 'json' | 'pdf' = 'csv',
  columns?: ExportColumn[]
) {
  let exportableData = data;
  
  // Filter columns if specified
  if (columns && columns.length > 0) {
    exportableData = data.map(row => {
      const filtered: any = {};
      columns.forEach(col => {
        const displayName = col.label || col.header;
        filtered[displayName] = row[col.key];
      });
      return filtered;
    });
  }
  
  switch (format) {
    case 'csv':
      await exportToCSV(exportableData, filename);
      break;
    case 'json':
      await exportToJSON(exportableData, filename);
      break;
    case 'pdf':
      await exportToPDF(exportableData, filename, filename);
      break;
  }
}
