import React, { useState, useMemo } from 'react';
import { Select, Spin, message } from 'antd';
import axios from 'axios';
import debounce from 'lodash/debounce';
import API_BASE_URL from '../config';
import { maskPhone } from '../utils/phoneMask';

const { Option } = Select;

const UserSearchSelect = ({ value, onChange, placeholder, style, leaderOnly = false }) => {
  const [fetching, setFetching] = useState(false);
  const [options, setOptions] = useState([]);

  const fetchUser = useMemo(
    () => debounce(async (search) => {
      if (!search || search.trim() === '') return;
      setFetching(true);
      try {
        const token = localStorage.getItem('token');
        if (!token) {
          message.error('登录已过期，请重新登录');
          return;
        }
        const params = { keyword: search };
        if (leaderOnly) {
          params.leaderOnly = 'true';
        }
        const response = await axios.get(`${API_BASE_URL}/api/users/search`, {
          params,
          headers: { Authorization: `Bearer ${token}` }
        });
        setOptions(response.data.map(user => ({
          label: `${user.real_name} (${maskPhone(user.phone)}) - ${user.department}`,
          value: JSON.stringify(user),
          key: user.phone
        })));
      } catch (error) {
        console.error('搜索用户失败', error);
        if (error.code === 'ERR_NETWORK') {
          message.error('无法连接到后端服务器，请检查后端是否启动（端口5000）');
        } else {
          // 仅在非网络错误时显示具体错误信息，避免干扰用户
          // message.error('搜索失败: ' + (error.response?.data?.message || error.message));
        }
      } finally {
        setFetching(false);
      }
    }, 500),
    [leaderOnly]
  );

  return (
    <Select
      showSearch
      value={value}
      placeholder={placeholder}
      onSearch={fetchUser}
      onChange={onChange}
      filterOption={false}
      notFoundContent={fetching ? <Spin size="small" /> : null}
      style={style}
    >
      {options.map(opt => (
        <Option key={opt.key} value={opt.value}>{opt.label}</Option>
      ))}
    </Select>
  );
};

export default UserSearchSelect;
