import { useState, useCallback } from 'react';
import { useSnackbar } from 'notistack';
import { employeeExportApi, type ExportEmployeesRequest } from '@/shared/api/endpoints/hr/employee-export';

export const useEmployeeExport = () => {
  const { enqueueSnackbar } = useSnackbar();
  const [isExporting, setIsExporting] = useState(false);
  const [exportProgress, setExportProgress] = useState<string>('');

  const startExport = useCallback(async (request: ExportEmployeesRequest) => {
    setIsExporting(true);
    setExportProgress('Démarrage de l\'export...');
    
    try {
      const response = await employeeExportApi.startExport(request);
      const filePath = response.data;
      
      setExportProgress('Export en cours...');
      enqueueSnackbar('Export démarré avec succès', { variant: 'success' });
      
      // Poll for export completion
      return await pollExportStatus(filePath);
      
    } catch (error: any) {
      console.error('Error starting export:', error);
      enqueueSnackbar('Erreur lors du démarrage de l\'export', { variant: 'error' });
      throw error;
    } finally {
      setIsExporting(false);
      setExportProgress('');
    }
  }, [enqueueSnackbar]);

  const pollExportStatus = useCallback(async (filePath: string): Promise<string> => {
    const maxAttempts = 30; // 30 seconds max
    let attempts = 0;
    
    while (attempts < maxAttempts) {
      try {
        const response = await employeeExportApi.getExportStatus(filePath);
        const status = response.data;
        
        if (status === 'READY') {
          setExportProgress('Export terminé');
          return filePath;
        } else if (status === 'ERROR') {
          throw new Error('Export failed');
        }
        
        // Wait 1 second before next check
        await new Promise(resolve => setTimeout(resolve, 1000));
        attempts++;
        setExportProgress(`Export en cours... (${attempts}/${maxAttempts})`);
        
      } catch (error) {
        console.error('Error checking export status:', error);
        throw error;
      }
    }
    
    throw new Error('Export timeout - please try again');
  }, []);

  const downloadExportFile = useCallback(async (filePath: string) => {
    try {
      setExportProgress('Téléchargement...');
      
      const blob = await employeeExportApi.downloadExportFile(filePath);
      
    
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      
      const filename = filePath.split('/').pop() || 'employee_export.csv';
      link.download = filename;
      
      
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
      
      enqueueSnackbar('Fichier téléchargé avec succès', { variant: 'success' });
      setExportProgress('');
      
    } catch (error: any) {
      console.error('Error downloading export file:', error);
      enqueueSnackbar('Erreur lors du téléchargement', { variant: 'error' });
      setExportProgress('');
      throw error;
    }
  }, [enqueueSnackbar]);

  const exportAndDownload = useCallback(async (request: ExportEmployeesRequest) => {
    try {
      const filePath = await startExport(request);
      await downloadExportFile(filePath);
    } catch (error) {
      console.error('Export and download failed:', error);
      throw error;
    }
  }, [startExport, downloadExportFile]);

  return {
    isExporting,
    exportProgress,
    startExport,
    downloadExportFile,
    exportAndDownload,
  };
};
