import Taro, { useShareAppMessage } from '@tarojs/taro';

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

import ListPlaceholder from '@/components/list-placeholder';
import { WithdrawStatusDescriptions } from '@/constants/partner';
import useInviteCode from '@/hooks/use-invite-code';
import { WithdrawRecord } from '@/types/partner';
import { logWithPrefix } from '@/utils/common';
import { formatMoney, formatTimestamp, getWithdrawList as requestData } from '@/utils/partner';
import { getCommonShareMessage } from '@/utils/share';

import './index.less';

const PREFIX = 'withdraw-record';
const log = logWithPrefix(PREFIX);
const FIRST_PAGE = 0;

export default function WithdrawRecords() {
  const inviteCode = useInviteCode();
  const [hasMore, setHasMore] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [loadingMore, setLoadingMore] = useState(false);
  const [loadMoreError, setLoadMoreError] = useState(false);
  const [dataList, setDataList] = useState<WithdrawRecord[]>([]);
  const currentPage = useRef<number>(FIRST_PAGE);

  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);
      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(() => {
    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);
      } catch (e) {
        setDataList([]);
        setHasMore(false);
        setLoadMoreError(true);
      } finally {
        log('visible changed, refresh list data end');
        setLoadingMore(false);
      }
    };
    refresh();
  }, []);

  Taro.showShareMenu({
    withShareTicket: true,
  });

  useShareAppMessage(() => {
    return getCommonShareMessage({ useCapture: false, inviteCode });
  });

  return (
    <div className={PREFIX}>
      <PullRefresh className={`${PREFIX}__pull-refresh`} loading={refreshing} onRefresh={handleRefresh}>
        <List hasMore={hasMore} onLoad={handleLoadMore} loading={loadingMore || refreshing} disabled={loadMoreError}>
          {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`}>{formatTimestamp(item.created)}</div>
                  <div className={`${PREFIX}__item-withdraw`}>
                    <div className={`${PREFIX}__item-money`}>{formatMoney(item.amt)}</div>
                    <div className={`${PREFIX}__item-status`}>{WithdrawStatusDescriptions[item.status]}</div>
                  </div>
                </div>
              </div>
            </div>
          ))}
          <ListPlaceholder hasMore={false} loadingMore={loadingMore} loadMoreError={loadMoreError} />
        </List>
      </PullRefresh>
    </div>
  );
}
