import { useEffect, useState } from 'react';
import { useAdapter } from '../provider';
import type { Person } from '../types';

/** A thread's members (for @mention autocomplete + highlighting). Empty if the adapter
 *  doesn't implement listMembers, or while loading. */
export function useMembers(threadId: string | null): Person[] {
  const adapter = useAdapter();
  const [members, setMembers] = useState<Person[]>([]);

  useEffect(() => {
    if (!threadId || !adapter.listMembers) {
      setMembers([]);
      return;
    }
    let alive = true;
    adapter
      .listMembers(threadId)
      .then((m) => {
        if (alive) setMembers(m);
      })
      .catch(() => {
        if (alive) setMembers([]);
      });
    return () => {
      alive = false;
    };
  }, [adapter, threadId]);

  return members;
}
