import { List, PullRefresh } from '@taroify/core';
import classNames from 'classnames';
import { useCallback, useEffect, useRef, useState } from 'react';

import ListPlaceholder from '@/components/list-placeholder';
import { InviteUserInfo } from '@/types/partner';
import { logWithPrefix } from '@/utils/common';
import { formatTimestamp, formatUserId, getPartnerInviteList as requestData } from '@/utils/partner';

import './index.less';

const PREFIX = 'partner-invite-list';
const log = logWithPrefix(PREFIX);

const FIRST_PAGE = 0;

function PartnerList(props: {
  refreshDisabled?: boolean;
  visible?: boolean;
  listHeight?: number;
  className?: string;
  onListEmpty?: () => void;
}) {
  const { className, listHeight, refreshDisabled, visible = true, onListEmpty } = props;
  const [hasMore, setHasMore] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [loadingMore, setLoadingMore] = useState(false);
  const [loadMoreError, setLoadMoreError] = useState(false);
  const [dataList, setDataList] = useState<InviteUserInfo[]>([]);
  const currentPage = useRef<number>(FIRST_PAGE);
  const onListEmptyRef = useRef(onListEmpty);

  const handleRefresh = useCallback(async () => {
    log('start pull refresh');
    try {
      setRefreshing(true);
      setLoadMoreError(false);
      const { content, totalPages } = await requestData({ page: 1 });
      setDataList(content);
      currentPage.current = 1;
      setHasMore(currentPage.current < totalPages);
      !content.length && onListEmptyRef.current?.();
      log('pull refresh success');
    } catch (e) {
      setDataList([]);
      setHasMore(false);
      setLoadMoreError(true);
      currentPage.current = FIRST_PAGE;
      log('pull refresh failed');
    } finally {
      setRefreshing(false);
    }
  }, []);

  const handleLoadMore = useCallback(async () => {
    log('start load more', hasMore);
    if (!hasMore) {
      return;
    }
    setLoadMoreError(false);
    setLoadingMore(true);
    try {
      const { totalPages, content } = await requestData({ page: currentPage.current + 1 });
      setDataList([...dataList, ...content]);
      currentPage.current = currentPage.current + 1;
      setHasMore(currentPage.current < totalPages);
      log('load more success');
    } catch (e) {
      setLoadMoreError(true);
      log('load more failed');
    } finally {
      setLoadingMore(false);
    }
  }, [dataList, hasMore]);

  useEffect(() => {
    onListEmptyRef.current = onListEmpty;
  }, [onListEmpty]);

  // 初始化数据&配置变更后刷新数据
  useEffect(() => {
    // 列表不可见时，先不做处理
    if (!visible) {
      log('visible changed, but is not visible, only clear list');
      return;
    }

    const refresh = async () => {
      log('visible changed, start refresh list data');
      try {
        setDataList([]);
        setLoadingMore(true);
        setLoadMoreError(false);
        const { totalPages, content } = await requestData({ page: 1 });
        setDataList(content);
        currentPage.current = 1;
        setHasMore(currentPage.current < totalPages);
        !content.length && onListEmptyRef.current?.();
      } catch (e) {
        setDataList([]);
        setHasMore(false);
        setLoadMoreError(true);
      } finally {
        log('visible changed, refresh list data end');
        setLoadingMore(false);
      }
    };
    refresh();
  }, [visible]);

  return (
    <div className={PREFIX}>
      <div className={`${PREFIX}__title`}>
        <div className={`${PREFIX}__title-time-id`}>邀请时间｜用户编号</div>
        <div className={`${PREFIX}__title-created`}>模卡</div>
        <div className={`${PREFIX}__title-joined`}>合伙人</div>
      </div>
      <PullRefresh
        className={classNames(`${PREFIX}__pull-refresh`, className)}
        loading={refreshing}
        onRefresh={handleRefresh}
        disabled={refreshDisabled}
      >
        <List
          hasMore={hasMore}
          onLoad={handleLoadMore}
          loading={loadingMore || refreshing}
          disabled={loadMoreError || !visible}
          fixedHeight={typeof listHeight !== 'undefined'}
          style={listHeight ? { height: `${listHeight}px` } : undefined}
        >
          {dataList.map(item => (
            <div className={`${PREFIX}__item`} key={item.id || item.userId}>
              <div className={`${PREFIX}__item-border`}>
                <div className={`${PREFIX}__item-content`}>
                  <div className={`${PREFIX}__item-time-id`}>
                    <div className={`${PREFIX}__item-time`}>{formatTimestamp(item.created)}</div>
                    <div className={`${PREFIX}__item-id`}>{formatUserId(item.userId)}</div>
                  </div>
                  <div className={`${PREFIX}__item-created`}>{item.isCreateResume ? '已创建' : '未创建'}</div>
                  <div className={`${PREFIX}__item-joined`}>{item.isPartner ? '已加入' : '未加入'}</div>
                </div>
              </div>
            </div>
          ))}
          <ListPlaceholder hasMore={false} loadingMore={loadingMore} loadMoreError={loadMoreError} />
        </List>
      </PullRefresh>
    </div>
  );
}

export default PartnerList;
