/**
 * Hook for managing CSV export functionality
 */

import { useState, useCallback } from 'react';
import { DateRange } from '@/services/dashboard.service';
import { exportLifecycleToCSV, exportActivityToCSV, exportAgingToCSV } from '../utils/csvExports';

export function useDetailedReportsExports() {
  const [exportingLifecycle, setExportingLifecycle] = useState(false);
  const [exportingActivity, setExportingActivity] = useState(false);
  const [exportingAging, setExportingAging] = useState(false);

  const handleExportLifecycle = useCallback(
    async (dateRange: DateRange, customStartDate?: Date, customEndDate?: Date) => {
      try {
        setExportingLifecycle(true);
        await exportLifecycleToCSV(dateRange, customStartDate, customEndDate);
      } catch (error: any) {
        console.error('Failed to export lifecycle data:', error);
        alert('Failed to export lifecycle data. Please try again.');
      } finally {
        setExportingLifecycle(false);
      }
    },
    []
  );

  const handleExportActivity = useCallback(
    async (
      dateRange: DateRange,
      customStartDate?: Date,
      customEndDate?: Date,
      filterCategory?: string,
      filterSeverity?: string
    ) => {
      try {
        setExportingActivity(true);
        await exportActivityToCSV(dateRange, customStartDate, customEndDate, filterCategory, filterSeverity);
      } catch (error: any) {
        console.error('Failed to export activity data:', error);
        alert('Failed to export activity data. Please try again.');
      } finally {
        setExportingActivity(false);
      }
    },
    []
  );

  const handleExportAging = useCallback(
    async (threshold: number, dateRange: DateRange, customStartDate?: Date, customEndDate?: Date) => {
      try {
        setExportingAging(true);
        await exportAgingToCSV(threshold, dateRange, customStartDate, customEndDate);
      } catch (error: any) {
        console.error('Failed to export aging data:', error);
        alert('Failed to export aging data. Please try again.');
      } finally {
        setExportingAging(false);
      }
    },
    []
  );

  return {
    exportingLifecycle,
    exportingActivity,
    exportingAging,
    handleExportLifecycle,
    handleExportActivity,
    handleExportAging,
  };
}

