import { useState, useEffect, useCallback } from 'react';
import { supabase } from '@/integrations/supabase/client';

export function useMonthEndReportData(associationId, startDate, endDate) {
  const [data, setData] = useState({
    arcApplications: [],
    bidsQuotes: [],
    callLogs: [],
    collections: [],
    estoppels: [],
    homeownerRequests: [],
    legalMatters: [],
    ownerUpdates: [],
    statusUpdates: [],
    violations: []
  });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const fetchData = useCallback(async () => {
    if (!associationId || !startDate || !endDate) return;

    setLoading(true);
    setError(null);

    try {
      const startISO = startDate.toISOString();
      const endISO = endDate.toISOString();

      const promises = [
        supabase.from('arc_applications').select('*').eq('association_id', associationId)
          .gte('created_at', startISO).lte('created_at', endISO).order('created_at', { ascending: false }),

        supabase.from('bids_quotes').select('*').eq('association_id', associationId)
          .gte('created_at', startISO).lte('created_at', endISO).order('created_at', { ascending: false }),

        supabase.from('call_logs').select('*').eq('association_id', associationId)
          .gte('created_at', startISO).lte('created_at', endISO).order('created_at', { ascending: false }),

        supabase.from('collections').select('*').eq('association_id', associationId)
          .order('updated_at', { ascending: false }),

        supabase.from('estoppels').select('*').eq('association_id', associationId)
          .gte('created_at', startISO).lte('created_at', endISO).order('created_at', { ascending: false }),

        supabase.from('homeowner_requests').select('*').eq('association_id', associationId)
          .order('updated_at', { ascending: false }),

        supabase.from('legal_matters').select('*').eq('association_id', associationId)
          .order('updated_at', { ascending: false }),

        supabase.from('owner_updates').select('*').eq('association_id', associationId)
          .gte('created_at', startISO).lte('created_at', endISO).order('created_at', { ascending: false }),

        supabase.from('status_updates').select('*').eq('association_id', associationId)
          .gte('created_at', startISO).lte('created_at', endISO).order('created_at', { ascending: false }),
      ];

      const results = await Promise.all(promises);
      const [arcRes, bidsRes, callsRes, colsRes, estRes, reqRes, legalRes, ownerUpdRes, statusUpdRes] = results;

      setData({
        arcApplications: arcRes.data || [],
        bidsQuotes: bidsRes.data || [],
        callLogs: callsRes.data || [],
        collections: colsRes.data || [],
        estoppels: estRes.data || [],
        homeownerRequests: reqRes.data || [],
        legalMatters: legalRes.data || [],
        ownerUpdates: ownerUpdRes.data || [],
        statusUpdates: statusUpdRes.data || [],
        violations: []
      });

    } catch (err) {
      console.error("Error fetching report data:", err);
      setError(err.message);
    } finally {
      setLoading(false);
    }
  }, [associationId, startDate, endDate]);

  useEffect(() => {
    fetchData();
  }, [fetchData]);

  return { data, loading, error, refetch: fetchData };
}
