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

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

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

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

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

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

// export default
export default ComponentSkillList;