
// import react
import { Virtuoso } from 'react-virtuoso';
import React, { useEffect, useState } from 'react';

// import local dependencies
import Loading from '../../Loading';
import ApiSignal from '../../../signals/Api';
import useResults from '../../../hooks/useResults';
import { useSignal } from '../../../signal';
import TeamMemberListItem from './Item';
import { current as TeamSignal } from '../../../signals/Teams';
import { removed as MemberRemovedSignal, created as MemberCreatedSignal } from '../Modal';

/**
 * component members
 *
 * @param props 
 */
const ComponentTeamMemberList = (props = {}) => {
  // signals
  const [api] = useSignal(ApiSignal);
  const [team] = useSignal(TeamSignal);

  // member created
  const [sCreated] = useSignal(MemberCreatedSignal);
  const [sRemoved] = useSignal(MemberRemovedSignal);
  
  // state
  const [ready, setReady] = useState(false);
  
  // items
  const {
    resetting,
    items : members,

    loadNext,
  } = useResults(api.Team.Member.list, 'members', {
    sort    : props.sort,
    team    : team?.id,
    search  : props.search,
    disable : !team?.id,
  }, null, props.onResult);

  // use effect
  useEffect(() => {
    // ready
    setReady(true);
  }, []);

  // items
  const actualItems = [
    ...members,
    ...sCreated,
  ].filter((m) => m.team === team?.id).reduce((accum, item) => {
    // check id in accum
    if (!accum.find((a) => a.id === item.id)) accum.push(item);

    // add to accum
    return accum;
  }, []).filter((m) => !sRemoved.includes(m.id));

  // return jsx
  return (
    <div className="flex-1 members">
      {(ready && !resetting) ? (
        <Virtuoso
          useWindowScroll

          data={actualItems}
          overscan={{
            main    : 2048,
            reverse : 2048,
          }}
          endReached={() => loadNext()}
          itemContent={(index, item) => (
            <TeamMemberListItem
              key={item.id}
              item={item}
            />
          )}
        />
      ) : (
        <div className="flex flex-1 justify-center items-center">
          <Loading />
        </div>
      )}
    </div>
  );
};

// export default
export default ComponentTeamMemberList;