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

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

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

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

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

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

// export default
export default ComponentSecretList;