import { Select } from 'antd';
import { useState, useCallback } from 'react';
import { patientApi } from '../../../api/health/patients';

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

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

  const genderMap: Record<string, string> = { male: '男', female: '女' };

  const handleSearch = useCallback(async (search: string) => {
    if (!search || search.length < 1) {
      setOptions([]);
      return;
    }
    setFetching(true);
    try {
      const result = await patientApi.list({
        search,
        page_size: 20,
      });
      setOptions(
        result.data.map((p) => ({
          value: p.id,
          label: `${p.name}${p.gender ? ` (${genderMap[p.gender] || p.gender})` : ''}`,
        })),
      );
    } 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
    />
  );
}
