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

/**
 * component keys
 *
 * @param props 
 */
const ComponentKeyList = (props = {}) => {
  // api
  const [api] = useSignal(ApiSignal);
  const [key] = useSignal(KeySignal);
  const [team] = useSignal(TeamSignal);
  
  // state
  const [ready, setReady] = useState(false);
  const [write, setWrite] = useState(false);
  
  // items
  const {
    resetting,
    items : keys,

    loadNext,
  } = useResults(api.Key.list, 'keys', {
    write,
    sort    : props.sort,
    team    : team?.id,
    search  : props.search,
    disable : !team?.id,
    current : key ? 'creating' : 'na',
  }, null, props.onResult);

  // use effect
  useEffect(() => {
    // ready
    setReady(true);
  }, []);
  useEffect(() => {
    // if key signal
    if (key) {
      // load next
      setWrite(true);
    }
  }, [key]);

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

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

// export default
export default ComponentKeyList;