import {ScrollView, Text} from '@tarojs/components';
import {useListEvent, useRefreshState, useScrollControl} from './hooks';
import {Empty} from '@components';
import classNames from 'classnames';

const Refresh = function ({
  isRefreshing,
  onRefresh,
  onLoading,
  isLoading,
  children,
  style,
  className,
  background,
  refreshStyle,
  noMore,
  empty,
  emptyMsg,
  emptyClassName,
  emptyChildren,
  endClassName,
}) {
  const [topRef, onScroll] = useScrollControl();
  const refreshState = useRefreshState(topRef, isRefreshing);
  const {onListRefresh, onListLoading} = useListEvent({
    isLoading,
    isRefreshing: refreshState,
    onRefresh,
    onLoading,
    noMore,
  });

  return (
    <ScrollView
      scrollY
      style={style}
      className={className}
      refresherEnabled
      refresherTriggered={refreshState}
      onRefresherRefresh={onListRefresh}
      onScrollToLower={onListLoading}
      refresherBackground={background ?? '#fff'}
      scrollTop={topRef.current}
      onScroll={onScroll}
      refresherDefaultStyle={refreshStyle}
    >
      {empty ? (
        <Empty msg={emptyMsg} className={emptyClassName}>
          {emptyChildren}
        </Empty>
      ) : (
        children
      )}

      <Text
        className={classNames('hidden text-sm text-center py-4 text-dark-3', {
          '!block': isLoading,
        })}
      >
        正在加载中
      </Text>

      <Text
        className={classNames(
          'hidden text-sm text-center py-4 text-dark-3',
          endClassName,
          {
            '!block': noMore && !isRefreshing && !isLoading && !empty,
          },
        )}
      >
        已经到底了~~
      </Text>
    </ScrollView>
  );
};

export default Refresh;
