import { useMemo, useRef, useState } from 'react'
import { Select, Spin } from 'antd'
import { debounce } from 'lodash-es'
import { getTeacherList } from '@/api/user'
function DebounceSelect({ fetchOptions, debounceTimeout = 800, ...props }) {
  const [fetching, setFetching] = useState(false)
  const [options, setOptions] = useState([])
  const fetchRef = useRef(0)
  const debounceFetcher = useMemo(() => {
    const loadOptions = (value) => {
      fetchRef.current += 1
      const fetchId = fetchRef.current
      setOptions([])
      setFetching(true)
      fetchOptions(value).then((newOptions) => {
        if (fetchId !== fetchRef.current) {
          // for fetch callback order
          return
        }
        setOptions(newOptions)
        setFetching(false)
      })
    }
    return debounce(loadOptions, debounceTimeout)
  }, [fetchOptions, debounceTimeout])
  return (
    <Select
      labelInValue
      filterOption={false}
      onSearch={debounceFetcher}
      notFoundContent={fetching ? <Spin size="small" /> : null}
      {...props}
      options={options}
    />
  )
}

// Usage of DebounceSelect

async function fetchUserList(username) {
  console.log('fetching user', username)
  return getTeacherList({ real_name: username, page_size: 40 }).then((res) => {
    return res.data.list.map((item) => {
      return { ...item, label: `${item.real_name} (${item.tel})` }
    })
  })
}

const SelectTeacher = (props) => {
  const [value, setValue] = useState([])
  return (
    <DebounceSelect
      mode="multiple"
      value={value}
      placeholder="Select users"
      fetchOptions={fetchUserList}
      fieldNames={{ label: 'label', value: 'id' }}
      onChange={(newValue) => {
        setValue(newValue)
      }}
      style={{ width: '100%' }}
      {...props}
    />
  )
}
export default SelectTeacher
