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

export function useHomeownerData(associationId) {
  const [homeowners, setHomeowners] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);

  useEffect(() => {
    if (!associationId) {
      setHomeowners([]);
      return;
    }

    const fetchHomeowners = async () => {
      setIsLoading(true);
      setError(null);
      try {
        const { data, error } = await supabase
          .from('owners')
          .select('*')
          .eq('association_id', associationId)
          .eq('status', 'active')
          .order('last_name');
        if (error) throw error;
        setHomeowners(data || []);
      } catch (err) {
        console.error('Error fetching homeowners:', err);
        setError(err);
      } finally {
        setIsLoading(false);
      }
    };

    fetchHomeowners();
  }, [associationId]);

  return { homeowners, isLoading, error };
}
