import { PlusOutlined } from '@ant-design/icons';
import type { InputRef, SelectProps } from 'antd';
import { Button, Divider, Input, Select, Space } from 'antd';
import { useRef, useState } from 'react';
import { withWarpFormItemProps } from '../DynamicForm/util';

export interface AddSelectProps extends SelectProps {
  /** 添加按钮名称 */
  addName?: string;
  /** 选项添加处理器，返回true表示清空input等收尾处理 */
  onOptionAdd: (inputVal: string) => boolean;
}

const AddSelect = (props: AddSelectProps) => {
  const { value, onChange, options, placeholder, disabled, addName, onOptionAdd } = props;
  const [addVal, setAddVal] = useState<string>('');
  const addInputRef = useRef<InputRef>(null);

  const addHandler = (e: React.MouseEvent) => {
    e.preventDefault();
    if (onOptionAdd(addVal)) {
      setAddVal('');
      setTimeout(() => {
        addInputRef.current?.focus();
      }, 0);
    }
  };

  return (
    <Select
      value={value}
      placeholder={placeholder}
      options={options}
      onChange={onChange}
      disabled={disabled}
      dropdownRender={(menu) => (
        <>
          {menu}
          <Divider style={{ margin: '8px 0' }} />
          <Space style={{ padding: '0 8px 4px' }}>
            <Input
              ref={addInputRef}
              value={addVal}
              onChange={(e) => setAddVal(e.target.value)}
              onKeyDown={(e) => e.stopPropagation()}
            />
            <Button
              type="text"
              icon={<PlusOutlined />}
              disabled={!addVal || !addVal.trim().length}
              onClick={addHandler}
            >
              {addName || 'Add item'}
            </Button>
          </Space>
        </>
      )}
    />
  );
};

export default withWarpFormItemProps<AddSelectProps>(AddSelect);
