
// 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 useResults from '../../../hooks/useResults';
import NodeListItem from './Item';
import { useSignal } from '../../../signal';
import { current as TeamSignal } from '../../../signals/Teams';

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

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

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

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

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

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

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

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

// export default
export default ComponentNodeList;