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

/**
 * component clients
 *
 * @param props 
 */
const ComponentClientList = (props = {}) => {
  // state
  const [ready, setReady] = useState(false);
  const [write, setWrite] = useState(false);

  // signals
  const [api] = useSignal(ApiSignal);
  const [team] = useSignal(TeamSignal);
  const [client] = useSignal(ClientSignal);
  
  // items
  const {
    key,
    resetting,
    items : clients,

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

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

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

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

// export default
export default ComponentClientList;