import { Button, Image } from '@tarojs/components';

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

import JobCard from '@/components/job-card';
import ListPlaceholder from '@/components/list-placeholder';
import { PageUrl } from '@/constants/app';
import { JobInfo, GetJobsRequest } from '@/types/job';
import { logWithPrefix } from '@/utils/common';
import { requestMyRecommendJobList } from '@/utils/job';
import { switchTab } from '@/utils/route';

import './index.less';

interface IRequestProps extends Partial<GetJobsRequest> {}

export interface IJobListProps extends IRequestProps {
  className?: string;
}

const PAGE_SIZE = 10;
const PREFIX = 'job-recommend-list';
const log = logWithPrefix(PREFIX);

function JobRecommendList(props: IJobListProps) {
  const { className } = props;
  const [loading, setLoading] = useState(false);
  const [loadError, setLoadError] = useState(false);
  const [dataList, setDataList] = useState<JobInfo[]>([]);
  const requestProps = useRef<IRequestProps>({});

  const handleClickAllJob = useCallback(() => {
    switchTab(PageUrl.Job);
  }, []);

  useEffect(() => {
    requestProps.current = { page: 1, pageSize: PAGE_SIZE };
  }, []);

  useEffect(() => {
    const refresh = async () => {
      log('start request list data');
      try {
        setDataList([]);
        setLoading(true);
        setLoadError(false);
        const { jobResults = [] } = await requestMyRecommendJobList({ ...requestProps.current });
        setDataList(jobResults);
      } catch (e) {
        setDataList([]);
        setLoadError(true);
      } finally {
        log('request list data end');
        setLoading(false);
      }
    };
    refresh();
  }, []);

  return (
    <div className={classNames(PREFIX, className)}>
      <div className={`${PREFIX}__header`}>
        <div className={`${PREFIX}__header-left-line`} />
        <Image className={`${PREFIX}__header-icon`} src={require('@/statics/svg/like.svg')} />
        <div className={`${PREFIX}__header-title`}>为你推荐附近通告</div>
        <div className={`${PREFIX}__header-right-line`} />
      </div>
      <List disabled>
        {dataList.map(item => (
          <JobCard data={item} key={item.id} redirectOpen />
        ))}
        <ListPlaceholder noMoreText="" loadingMore={loading} loadMoreError={loadError} loadMoreErrorText="加载失败" />
      </List>
      <Button className={`${PREFIX}__more-button`} onClick={handleClickAllJob}>
        查看更多通告
      </Button>
    </div>
  );
}

export default JobRecommendList;
