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

import GroupCard from '@/components/group-card';
import ListPlaceholder from '@/components/list-placeholder';
import { GroupInfo, GetGroupsRequest } from '@/types/group';
import { logWithPrefix } from '@/utils/common';
import { requestGroupList } from '@/utils/group';

import './index.less';

interface IRequestProps extends GetGroupsRequest {}

export interface IGroupListProps extends IRequestProps {
  refreshDisabled?: boolean;
  listHeight?: number;
  className?: string;
  onListEmpty?: () => void;
  onClickInvite: (data: GroupInfo) => void;
}

const FIRST_PAGE = 0;
const PAGE_SIZE = 40;
const PREFIX = 'group-list';
const log = logWithPrefix(PREFIX);

function JobList(props: IGroupListProps) {
  const { className, listHeight, refreshDisabled, type, imGroupNick, status, onListEmpty, onClickInvite } = props;
  const [refreshing, setRefreshing] = useState(false);
  const [hasMore, setHasMore] = useState(true);
  const [loadingMore, setLoadingMore] = useState(false);
  const [loadMoreError, setLoadMoreError] = useState(false);
  const [dataList, setDataList] = useState<GroupInfo[]>([]);
  const currentPage = useRef<number>(FIRST_PAGE);
  const requestProps = useRef<IRequestProps>({ type });
  const onListEmptyRef = useRef(onListEmpty);

  const handleRefresh = useCallback(async () => {
    log('start pull refresh');
    try {
      setRefreshing(true);
      setLoadMoreError(false);
      const { page, hasMore: more, groupResults } = await requestGroupList({ ...requestProps.current, page: 1 });
      setHasMore(more);
      setDataList(groupResults);
      currentPage.current = page;
      !groupResults.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 {
        page,
        hasMore: more,
        groupResults,
      } = await requestGroupList({ ...requestProps.current, page: currentPage.current + 1 });
      setDataList([...dataList, ...groupResults]);
      setHasMore(more);
      currentPage.current = page;
      log('load more success');
    } catch (e) {
      setLoadMoreError(true);
      log('load more failed');
    } finally {
      setLoadingMore(false);
    }
  }, [dataList, currentPage, hasMore]);

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

  useEffect(() => {
    log('request params changed');
    requestProps.current = {
      type,
      status,
      imGroupNick: imGroupNick ? imGroupNick.trim() : undefined,
      pageSize: PAGE_SIZE,
    };
  }, [type, status, imGroupNick]);

  useEffect(() => {
    const refresh = async () => {
      log('props changed, start refresh list data');
      try {
        setDataList([]);
        setLoadingMore(true);
        setLoadMoreError(false);
        const { page, hasMore: more, groupResults } = await requestGroupList({ ...requestProps.current, page: 1 });
        setHasMore(more);
        setDataList(groupResults);
        currentPage.current = page;
        !groupResults.length && onListEmptyRef.current?.();
      } catch (e) {
        setDataList([]);
        setHasMore(false);
        setLoadMoreError(true);
        currentPage.current = FIRST_PAGE;
      } finally {
        log('props changed, refresh list data end');
        setLoadingMore(false);
      }
    };
    refresh();
  }, [type, status, imGroupNick]);

  return (
    <PullRefresh
      className={classNames(`${PREFIX}__pull-refresh`, className)}
      loading={refreshing}
      onRefresh={handleRefresh}
      disabled={refreshDisabled}
    >
      <List
        hasMore={hasMore}
        onLoad={handleLoadMore}
        loading={loadingMore || refreshing}
        disabled={loadMoreError}
        fixedHeight={typeof listHeight !== 'undefined'}
        style={listHeight ? { height: `${listHeight}px` } : undefined}
      >
        {dataList.map(item => (
          <GroupCard type={type} data={item} key={item.blGroupId} onClick={() => onClickInvite(item)} />
        ))}
        <ListPlaceholder hasMore={hasMore} loadingMore={loadingMore} loadMoreError={loadMoreError} />
      </List>
    </PullRefresh>
  );
}

export default JobList;
