import { Select } from 'antd';
import { useState, useCallback, useEffect } from 'react';
import { doctorApi } from '../../../api/health/doctors';

interface Props {
  value?: string;
  onChange?: (value: string, label: string) => void;
  placeholder?: string;
}

export function DoctorSelect({ value, onChange, placeholder }: Props) {
  const [options, setOptions] = useState<
    { value: string; label: string }[]
  >([]);
  const [fetching, setFetching] = useState(false);

  useEffect(() => {
    let cancelled = false;
    doctorApi.list({ page_size: 50 }).then((result) => {
      if (!cancelled) {
        setOptions(
          result.data.map((d) => ({
            value: d.id,
            label: `${d.name}${d.department ? ` - ${d.department}` : ''}`,
          })),
        );
      }
    }).catch((err) => console.warn('[DoctorSelect] 获取医生列表失败:', err));
    return () => { cancelled = true; };
  }, []);

  const handleSearch = useCallback(async (search: string) => {
    if (!search || search.length < 1) {
      return;
    }
    setFetching(true);
    try {
      const result = await doctorApi.list({
        search,
        page_size: 20,
      });
      setOptions(
        result.data.map((d) => ({
          value: d.id,
          label: `${d.name}${d.department ? ` - ${d.department}` : ''}`,
        })),
      );
    } catch {
      // 搜索失败时保留初始列表
    } finally {
      setFetching(false);
    }
  }, []);

  return (
    <Select
      showSearch
      filterOption={false}
      onSearch={handleSearch}
      onChange={(val) => {
        const opt = options.find((o) => o.value === val);
        onChange?.(val, opt?.label ?? '');
      }}
      loading={fetching}
      options={options}
      value={value}
      placeholder={placeholder ?? '搜索医护'}
      allowClear
    />
  );
}
