import type {
  ParamsType,
  ProFormSelectProps,
} from '@ant-design/pro-components';
import { ProFormSelect } from '@ant-design/pro-components';
import React, {
  forwardRef,
  useEffect,
  useImperativeHandle,
  useState,
} from 'react';
import '../index.less';

interface IProFormBizSelectProps extends ProFormSelectProps {
  params?: ParamsType;
  fetchOptions: (params?: ParamsType) => Promise<ProFormSelectProps['options']>;
}

export interface ProFormBizSelectHandles {
  reload: () => Promise<void>;
}

const ProFormBizSelect = forwardRef<
  ProFormBizSelectHandles,
  IProFormBizSelectProps
>(({ params, fetchOptions, ...rest }, ref) => {
  const [options, setOptions] = useState<ProFormSelectProps['options']>();

  const init = async (params?: ParamsType) => {
    const data = await fetchOptions(params);
    setOptions(data);
  };

  useEffect(() => {
    if (params) {
      init(params).then();
    }
  }, []);

  useImperativeHandle(ref, () => ({
    reload: async () => {
      await init(params);
    },
  }));

  return <ProFormSelect options={options} {...rest} />;
});

export default ProFormBizSelect;
