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

export function useOwnerUpdate(associationId) {
  const [updates, setUpdates] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const { toast } = useToast();

  const fetchUpdates = useCallback(async () => {
    if (!associationId) return;
    
    setLoading(true);
    setError(null);
    try {
      const { data, error: fetchError } = await supabase
        .from('owner_updates')
        .select('*')
        .eq('association_id', associationId)
        .order('created_at', { ascending: false });

      if (fetchError) throw fetchError;
      setUpdates(data || []);
    } catch (err) {
      console.error('Error fetching owner updates:', err);
      const msg = 'Failed to load owner updates. Please try again.';
      setError(msg);
      toast({ variant: 'destructive', title: 'Error', description: msg });
      setUpdates([]);
    } finally {
      setLoading(false);
    }
  }, [associationId, toast]);

  return { updates, loading, error, fetchUpdates };
}
