
// import react
import React, { memo, useEffect, useState } from 'react';
import { Masonry, useInfiniteLoader } from 'masonic';

// import local dependencies
import Loading from '../../Loading';
import ApiSignal from '../../../signals/Api';
import NodeListItem from './Item';
import { useSignal } from '../../../signal';
import { useAgents } from '../../../data/useAgent';
import { current as TeamSignal } from '../../../signals/Teams';

/**
 * render item
 *
 * @param param0 
 */
const ComponentAgentListItem = memo(({ index, data }) => {

  // return jsx
  return (
    <NodeListItem
      {...data}
    />
  );
});

/**
 * component nodes
 *
 * @param props 
 */
const ComponentAgentList = (props = {}) => {
  // signals
  const [api] = useSignal(ApiSignal);
  const [team] = useSignal(TeamSignal);
  
  // state
  const [ready, setReady] = useState(false);
  
  // items
  const {
    key,
    agents,

    loadMore
  } = useAgents({
    team    : team?.id,
    sort    : props.sort,
    search  : props.search,
  }, {
    disable : !team?.id,
  });

  // maybe load more
  const maybeLoadMore = useInfiniteLoader(() => loadMore(), {
    isItemLoaded : (index, items) => !!items[index],
  });

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

  // return jsx
  return (
    <div className="flex-1 agents">
      {ready ? (
        <Masonry
          key={props.key || key}
          items={(props.agents || agents).map((item) => {

            // return item
            return {
              item,
            };
          })}
          render={ComponentAgentListItem}
          itemKey={(data, index) => data?.brain?.id || index}
          onRender={props.agents ? undefined : maybeLoadMore}
          columnWidth={384}
          columnGutter={16}
        />
      ) : (
        <div className="flex flex-1 justify-center items-center">
          <Loading />
        </div>
      )}
    </div>
  );
};

// export default
export default ComponentAgentList;