import { CloseOutlined } from '@ant-design/icons';
import { Input } from 'antd';
import styles from './index.less';

type ParameterInputData = {
  value?: any;
  showValue?: any;
  fromSelect?: boolean;
} & Record<string, any>;

interface ParameterInputProps {
  value?: ParameterInputData;
  onChange?: (value: ParameterInputData) => void;
  onClick?: () => void;
  canInput?: boolean;
  textArea?: boolean;
  placeholder?: string;
  allowClear?: boolean;
}

function ParameterInput({
  value,
  onChange,
  onClick,
  canInput = true,
  textArea = false,
  placeholder,
  allowClear,
  ...rest
}: ParameterInputProps) {
  // console.log('ParameterInput', value);

  const valueObj =
    typeof value === 'string' ? { value: value, fromSelect: false, showValue: value } : value;
  if (valueObj && !valueObj.showValue) {
    valueObj.showValue = valueObj.value;
  }
  const isSelect = valueObj?.fromSelect;
  const InputComponent = textArea ? Input.TextArea : Input;

  return (
    <>
      {isSelect || !canInput ? (
        <div className={styles['parameter-input']} onClick={onClick}>
          {valueObj?.showValue ? (
            <div className={styles['parameter-input__content']}>
              <span className={styles['parameter-input__content__value']}>
                {valueObj?.showValue}
              </span>
              <CloseOutlined
                className={styles['parameter-input__content__close-icon']}
                onClick={() =>
                  onChange?.({
                    ...valueObj,
                    fromSelect: false,
                    value: undefined,
                    showValue: undefined,
                  })
                }
              />
            </div>
          ) : (
            <div className={styles['parameter-input__placeholder']}>{placeholder}</div>
          )}
        </div>
      ) : (
        <InputComponent
          {...rest}
          placeholder={placeholder}
          allowClear={allowClear}
          value={valueObj?.showValue}
          onChange={(e) =>
            onChange?.({
              ...valueObj,
              fromSelect: false,
              value: e.target.value,
              showValue: e.target.value,
            })
          }
        />
      )}
    </>
  );
}

export default ParameterInput;
