import { useState, useCallback } from 'react';
import { supabase } from '@/integrations/supabase/client';
import { useToast } from '@/components/ui/use-toast';

export function useComprehensiveReportData() {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);
  const { toast } = useToast();

  const generateData = useCallback(async (associationId, startDate, endDate, sections) => {
    setLoading(true);
    setError(null);
    try {
      const reportData = {};
      
      if (sections?.includes('ownerUpdates')) {
        try {
          const { data: ouData, error: ouError } = await supabase
            .from('owner_updates')
            .select('*')
            .eq('association_id', associationId)
            .gte('created_at', startDate.toISOString())
            .lte('created_at', endDate.toISOString());

          if (ouError) throw ouError;
          reportData.ownerUpdates = ouData || [];
        } catch (err) {
          console.error('Error fetching owner updates for report:', err);
          toast({ variant: 'destructive', title: 'Data Error', description: 'Failed to load owner updates for report.' });
          reportData.ownerUpdates = [];
        }
      }

      setData(reportData);
      return reportData;
    } catch (err) {
      console.error('Fatal error generating comprehensive report data:', err);
      setError(err.message);
      toast({ variant: 'destructive', title: 'Report Error', description: 'A critical error occurred while fetching report data.' });
      return null;
    } finally {
      setLoading(false);
    }
  }, [toast]);

  return { loading, data, error, generateData };
}
