import { useState, useEffect, useCallback } from 'react';
import { supabase } from '@/integrations/supabase/client';
import { useAuth } from '@/contexts/AuthContext';
import { useToast } from '@/hooks/use-toast';

export function useUnits() {
  const [units, setUnits] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const { userRole } = useAuth();
  const { toast } = useToast();

  const fetchUnits = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      let query = supabase
        .from('property_owners')
        .select(`
          id,
          owner_name,
          property_address,
          unit_id,
          clients (id, name)
        `)
        .order('owner_name');

      if (userRole?.role === 'client' && userRole?.client_id) {
        query = query.eq('client_id', userRole.client_id);
      }

      const { data, error: fetchError } = await query;

      if (fetchError) throw fetchError;
      setUnits(data || []);
    } catch (err) {
      console.error('Error fetching units:', err);
      setError(err.message);
      toast({
        variant: 'destructive',
        title: 'Error loading units',
        description: err.message,
      });
    } finally {
      setLoading(false);
    }
  }, [userRole, toast]);

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

  return { units, loading, error, refetch: fetchUnits };
}
