import React, { forwardRef, ForwardRefRenderFunction } from 'react';
import classNames from 'classnames';
import { isFunction } from '@alifd/meet-react/es/utils';
import View from '@alifd/meet-react/es/view';
import BaseSelect from './BaseSelect';
import { ExtraSelectProps } from './type';
import { getPreviewValue } from '@alifd/meet-react/es/select/util';

const CustomSelect: ForwardRefRenderFunction<any, ExtraSelectProps> = (props, ref) => {
  const {
    isPreview,
    previewClassName: previewClassNameProp,
    previewStyle,
    renderPreview,
    prefix = 'mt-',
    size = 'medium',
  } = props;
  // notice: if mode=single, will return a non-array value
  const values = getPreviewValue(props);
  const previewClassName = classNames(previewClassNameProp, `${prefix}form-item-input--preview-${size}`);

  // render preview element
  if (isPreview) {
    if (isFunction(renderPreview)) {
      return (
        <View className={previewClassName} style={previewStyle}>
          {renderPreview(values, props)}
        </View>
      );
    }

    let directRenderVal: any = '';

    if (Array.isArray(values)) {
      directRenderVal = values.map((v) => v.label).join(',');
    } else if (values && values.label) {
      directRenderVal = values.label;
    }

    return (
      <div className={previewClassName} style={previewStyle}>
        {directRenderVal}
      </div>
    );
  }

  return <BaseSelect {...props} ref={ref} />;
};

export default forwardRef(CustomSelect);
