import { useState, useEffect, useCallback, useRef } from 'react';
import { getUsers, getPublicUsers } from '../services/users';

export const useUsers = (isAdmin = false) => {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [pagination, setPagination] = useState({
    page: 1,
    limit: 50,
    total: 0,
    pages: 0,
    hasMore: true
  });

  // Keep a ref so callbacks always call the latest fetchUsers
  const fetchUsersRef = useRef(null);

  const fetchUsers = useCallback(async (page = 1, reset = false, filters = {}) => {
    setLoading(true);
    setError(null);

    const params = {
      page,
      limit: 50,
      ...filters
    };

    const result = isAdmin ? await getUsers(params) : await getPublicUsers(params);

    if (result.success) {
      setUsers(prev => reset ? result.data : [...prev, ...result.data]);
      setPagination(result.pagination);
    } else {
      setError(result.message);
    }
    setLoading(false);
  }, [isAdmin]);

  fetchUsersRef.current = fetchUsers;

  useEffect(() => {
    fetchUsers(1, true); // Initial load, reset users
  }, [fetchUsers]);

  const loadMore = useCallback(() => {
    if (pagination.hasMore && !loading) {
      fetchUsersRef.current(pagination.page + 1, false);
    }
  }, [pagination, loading]);

  const refetch = useCallback((filters = {}) => {
    fetchUsersRef.current(1, true, filters);
  }, []);

  return {
    users,
    loading,
    error,
    pagination,
    loadMore,
    refetch
  };
};

