// Export Button Component
import { useState } from 'react';
import Button from './Button';
import { exportToCSV, exportToJSON, formatDataForExport } from '@/utils/export';
import type { Column } from './DataTable';
import { MdDownload, MdFileDownload } from 'react-icons/md';
import './ExportButton.css';

interface ExportButtonProps<T extends Record<string, any>> {
  data: T[];
  columns: Column<T>[];
  filename?: string;
  exportType?: 'csv' | 'json' | 'both';
  variant?: 'primary' | 'secondary' | 'ghost';
  size?: 'small' | 'medium' | 'large';
}

export default function ExportButton<T extends Record<string, any>>({
  data,
  columns,
  filename = 'export',
  exportType = 'csv',
  variant = 'secondary',
  size = 'small',
}: ExportButtonProps<T>) {
  const [isExporting, setIsExporting] = useState(false);

  const handleExport = async (type: 'csv' | 'json') => {
    setIsExporting(true);
    try {
      const exportData = formatDataForExport(data, columns);
      if (type === 'csv') {
        exportToCSV(exportData, `${filename}.csv`);
      } else {
        exportToJSON(exportData, `${filename}.json`);
      }
    } catch (error) {
      console.error('Export failed:', error);
    } finally {
      setIsExporting(false);
    }
  };

  if (exportType === 'both') {
    return (
      <div className="export-button-group">
        <Button
          variant={variant}
          size={size}
          onClick={() => handleExport('csv')}
          loading={isExporting}
          icon={<MdDownload />}
        >
          Export CSV
        </Button>
        <Button
          variant={variant}
          size={size}
          onClick={() => handleExport('json')}
          loading={isExporting}
          icon={<MdFileDownload />}
        >
          Export JSON
        </Button>
      </div>
    );
  }

  return (
    <Button
      variant={variant}
      size={size}
      onClick={() => handleExport(exportType)}
      loading={isExporting}
      icon={<MdDownload />}
    >
      Export {exportType.toUpperCase()}
    </Button>
  );
}

