'use client';

import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Download, FileSpreadsheet } from 'lucide-react';
import { generateVoteExport, downloadExportFile, formatFilename, ExportData, AnonymizationLevel } from '@/lib/export-utils';
import { settingsService } from '@/lib/services';

interface ExportStatsButtonProps {
  campaignTitle: string;
  propositions: any[];
  participants: any[];
  votes: any[];
  budgetPerUser: number;
  propositionStats?: any[];
  disabled?: boolean;
}

export function ExportStatsButton({
  campaignTitle,
  propositions,
  participants,
  votes,
  budgetPerUser,
  propositionStats,
  disabled = false
}: ExportStatsButtonProps) {
  const [isExporting, setIsExporting] = useState(false);

  const handleExport = async () => {
    if (disabled || isExporting) return;

    setIsExporting(true);

    try {
      // Récupérer le niveau d'anonymisation depuis les paramètres
      const anonymizationLevel = await settingsService.getStringValue('export_anonymization', 'full') as AnonymizationLevel;

      const exportData: ExportData = {
        campaignTitle,
        propositions,
        participants,
        votes,
        budgetPerUser,
        propositionStats,
        anonymizationLevel
      };

      const { data, format } = await generateVoteExport(exportData);
      const filename = formatFilename(campaignTitle, format);
      
      downloadExportFile(data, filename, format);
    } catch (error) {
      console.error('Erreur lors de l\'export:', error);
      // Ici on pourrait ajouter une notification d'erreur
    } finally {
      setIsExporting(false);
    }
  };



  return (
    <Button
      onClick={handleExport}
      disabled={disabled || isExporting}
      variant="outline"
      className="gap-2"
    >
      {isExporting ? (
        <>
          <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-current"></div>
          Export en cours...
        </>
      ) : (
        <>
          <FileSpreadsheet className="h-4 w-4" />
          Exporter les votes
        </>
      )}
    </Button>
  );
}
