import { Image } from '@tarojs/components';
import { NodesRef } from '@tarojs/taro';

import classNames from 'classnames';
import { useCallback, useEffect, useState } from 'react';

import JobList from '@/components/job-list';
import { APP_TAB_BAR_ID } from '@/constants/app';
import useListHeight, { IUseListHeightProps } from '@/hooks/use-list-height';
import { logWithPrefix } from '@/utils/common';

import './index.less';

interface IProps {
  visible: boolean;
}

const PREFIX = 'my-follow-job-fragment';
const LIST_CONTAINER_CLASS = 'my-follow-job-fragment-list-container';
const CALC_LIST_PROPS: IUseListHeightProps = {
  selectors: [`.${LIST_CONTAINER_CLASS}`, `#${APP_TAB_BAR_ID}`],
  calc: (rects: [NodesRef.BoundingClientRectCallbackResult, NodesRef.BoundingClientRectCallbackResult]) => {
    const [rect, diffRect] = rects;
    return diffRect.top - rect.top;
  },
};
const log = logWithPrefix(PREFIX);

const NoFollowTips = (props: { className?: string; height?: number }) => {
  const { className, height } = props;
  return (
    <div className={classNames(`${PREFIX}__empty-container`, className)} style={height ? { height } : undefined}>
      <Image className={`${PREFIX}__empty-box`} src={require('@/statics/svg/empty-box.svg')} mode="aspectFit" />
      <div className={`${PREFIX}__empty-text`}>暂无关注的群</div>
    </div>
  );
};

function MyFollowFragment(props: IProps) {
  const { visible } = props;
  const [isEmpty, setIsEmpty] = useState(false);
  const listHeight = useListHeight(CALC_LIST_PROPS);
  log('list height', listHeight);

  const handleListEmpty = useCallback(() => {
    setIsEmpty(true);
  }, []);

  useEffect(() => {
    if (visible) {
      setIsEmpty(false);
    }
  }, [visible]);

  if (isEmpty) {
    return <NoFollowTips className={LIST_CONTAINER_CLASS} height={listHeight} />;
  }

  return (
    <div className={PREFIX}>
      <JobList
        visible
        isFollow
        className={LIST_CONTAINER_CLASS}
        listHeight={listHeight}
        onListEmpty={handleListEmpty}
      />
    </div>
  );
}

export default MyFollowFragment;
