import React, { useState, useEffect } from 'react';
import { Select, Empty } from '@sensoro/sensoro-design';
import { Spin } from 'antd';
import { LoadingOutlined } from '@ant-design/icons';
import VisibilitySensor from 'react-visibility-sensor';
import classNames from '@pansy/classnames';
import IconFont from '@sensoro/library/lib/components/icon-font';
import styles from './index.less';

const antIcon = <LoadingOutlined style={{ fontSize: 24 }} spin />;
enum State {
  NORMAL,
  LOADING,
  FAILED,
  FINISH,
}

export interface ListProps {
  className?: string;
  style?: React.CSSProperties;
  loading?: boolean;
  total?: number;
  onLoadMore?: () => Promise<any>;
  empty?: React.ReactNode;
}

const List: React.FC<ListProps> = props => {
  const {
    className,
    children,
    total,
    onLoadMore,
    empty = (
      <Empty
        description="暂无预警"
        className={styles.noContent}
        icon={<IconFont type="icon-no-alarm" />}
      />
    ),
    ...rest
  } = props;
  const count = React.Children.count(children);
  const [state, setState] = React.useState<State>(
    count === total ? State.FINISH : State.NORMAL,
  );

  function onChange(isVisible: boolean) {
    onEnd?.();
  }

  const onEnd = async () => {
    if (state !== State.LOADING && typeof onLoadMore === 'function') {
      if (count === total) {
        setState(State.FINISH);
      } else {
        setState(State.LOADING);
        const success = await onLoadMore?.();
        if (success) {
          if (count === total) {
            setState(State.FINISH);
          } else {
            setState(State.NORMAL);
          }
        } else {
          setState(State.FAILED);
        }
      }
    }
  };

  return (
    <div className={classNames(styles.wrapper, className)} {...rest}>
      <div className={styles.contentWrapper}>{children}</div>

      <div>
        {total === 0 ? (
          empty
        ) : (
          <div style={{ minHeight: 128 }}>
            <VisibilitySensor onChange={onChange}>
              <div className={styles.state}>
                {state === State.LOADING && (
                  <div>
                    <Spin indicator={antIcon} style={{ marginRight: 16 }} />{' '}
                    加载中...
                  </div>
                )}
                {state === State.FAILED && (
                  <div>
                    加载失败, <a onClick={() => onEnd()}>重新加载</a>
                  </div>
                )}
                {state === State.FINISH && <div>没有更多了</div>}
              </div>
            </VisibilitySensor>
          </div>
        )}
      </div>
    </div>
  );
};

export default List;
