import React, { useState, useRef, useEffect, useCallback } from "react";
import { Select, LoadingTip, EmptyTip } from "@tencent/tea-component";

const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

const MAX_PAGE = 4;

export default function SelectLoadMoreExample() {
  const [first, setFirst] = useState(true);
  const [loading, setLoading] = useState(false);
  const [options, setOptions] = useState([]);

  const [keyword, setKeyword] = useState("");
  const [page, setPage] = useState(1);

  const timerRef = useRef(null);

  const fetch = useCallback(() => {
    if (timerRef.current) {
      clearTimeout(timerRef.current);
      timerRef.current = null;
    }

    const id = setTimeout(mock, 300);
    timerRef.current = id;

    async function mock() {
      await sleep(1000);

      if (id !== timerRef.current) {
        return;
      }

      const res = Array(10)
        .fill(null)
        .map((_, i) => ({
          value: `${keyword}${(page - 1) * 10 + i}`,
          text: `选项${(page - 1) * 10 + i} ${keyword}`,
        }));

      if (page === 1) {
        setOptions(res);
      } else {
        setOptions(options => [...options, ...res]);
      }

      setLoading(false);
    }

    setLoading(true);
  }, [keyword, page]);

  useEffect(() => {
    if (!first) {
      fetch();
    }
  }, [fetch, first, keyword, page]);

  return (
    <Select
      searchable
      matchButtonWidth
      size="m"
      appearance="button"
      filter={() => true}
      autoClearSearchValue={false}
      onOpen={() => {
        setFirst(false);
      }}
      onSearch={value => {
        setKeyword(value);
        setPage(1);
        setOptions([]);
      }}
      onScrollBottom={() => {
        if (!loading && page < MAX_PAGE) {
          setPage(page => page + 1);
        }
      }}
      options={options || []}
      onChange={value => console.log(value)}
      tips="共 40 项"
      bottomTips={loading && <LoadingTip />}
    />
  );
}
