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

export function useAllSupabaseUsers() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  const fetchUsers = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const { data, error: fetchError } = await supabase
        .from('profiles')
        .select('id, user_id, full_name, avatar_url, created_at, updated_at');

      if (fetchError) throw fetchError;

      const normalizedUsers = (data || []).map(u => ({
        id: u.user_id,
        name: u.full_name || 'Unknown User',
        avatar_url: u.avatar_url,
        created_at: u.created_at,
        raw_user: u
      }));

      setUsers(normalizedUsers);
    } catch (err) {
      console.error('[useAllSupabaseUsers] Error fetching users:', err);
      setError(err.message || 'An error occurred while fetching users.');
    } finally {
      setLoading(false);
    }
  }, []);

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

  return { users, loading, error, refresh: fetchUsers, retry: fetchUsers, setUsers };
}
