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

// import local dependencies
import Loading from '../../Loading';
import useTeam from '../../../hooks/useTeam';
import ApiSignal from '../../../signals/Api';
import useResults from '../../../hooks/useResults';
import { useSignal } from '../../../signal';
import WorkflowListItem from './Item';
import { current as TeamSignal } from '../../../signals/Teams';

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

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

/**
 * component workflows
 *
 * @param props 
 */
const ComponentWorkflowList = (props = {}) => {
  // signals
  const [sApi] = useSignal(ApiSignal);

  // use team
  const team = useTeam();
  
  // state
  const [ready, setReady] = useState(false);
  
  // items
  const {
    key,
    resetting,
    items : workflows,

    loadNext,
  } = useResults(sApi.Workflow.list, 'workflows', {
    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 workflows">
      {(ready && !resetting) ? (
        <Masonry
          key={props.key || key}
          items={(props.workflows || workflows).map((item) => {

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

// export default
export default ComponentWorkflowList;