import classNames from 'classnames';
import React, {
  useCallback,
  useContext,
  useEffect,
  useMemo,
  useState,
} from 'react';
import { Icon } from '../Icon';
import { ConfigProvider, Select as AntdSelect, SelectProps } from 'antd';
import './index.less';
import { AOP } from '../utils/AOP';

import { SelectHandler } from 'rc-select/lib/Select';
import { DefaultOptionType, LabeledValue } from 'antd/lib/select';

const Select = (props: SelectProps) => {
  const { getPrefixCls } = useContext(ConfigProvider.ConfigContext);
  const prefixCls = getPrefixCls('btri-select');
  // 为了与 antd 的生态保持兼容性，我们要求必须要使用 `.@{ant-prefix}` 变量来生成类名
  const { suffixIcon, removeIcon, loading } = props;
  const customSuffixIcon = useMemo(() => {
    return loading
      ? {
          suffixIcon: (
            <Icon iconName="Loading" style={{ fontSize: '16px' }} spin></Icon>
          ),
        }
      : suffixIcon
      ? { suffixIcon }
      : {
          suffixIcon: (
            <Icon iconName={'Down'} style={{ fontSize: '16px' }}></Icon>
          ),
        };
  }, [loading, suffixIcon]);
  const [_value, setValue] = useState(props.value);

  useEffect(() => {
    setValue(props.value);
  }, [props.value]);

  const _onChange = useCallback(
    (selected: any, option: DefaultOptionType | DefaultOptionType[]) => {
      setValue(selected);
      props.onChange?.(selected, option);
    },
    [props.onChange],
  );

  return (
    <AntdSelect
      showArrow={true}
      {...props}
      className={classNames(`${prefixCls}-box`, props.className)}
      popupClassName={classNames(
        `${prefixCls}-select-dropdown`,
        props.popupClassName,
      )}
      // removeIcon={
      //   removeIcon ? (
      //     removeIcon
      //   ) : (
      //     <Icon iconName="CloseSmall" style={{ fontSize: '16px' }}></Icon>
      //   )
      // }

      {...customSuffixIcon}
      onChange={_onChange}
    >
      {props.children}
    </AntdSelect>
  );
};

const Loading = () => {
  const { getPrefixCls } = useContext(ConfigProvider.ConfigContext);
  const prefixCls = getPrefixCls('btri-select');
  return <div className={classNames(`${prefixCls}-loading`)}>加载中</div>;
};

Select.Option = AntdSelect.Option;
Select.OptGroup = AntdSelect.OptGroup;
Select.Loading = Loading;

export { Select };
