import * as React from 'react';
import * as PropTypes from 'prop-types';
import { Button as TeaButton, ConfigProvider } from 'tea-component';
import classNames from '../../utils/classnames';

import './index.css';

import { usePlatform } from '../../utils/platform';

// 不用 react-weui 而直接用底层实现的原因是 react-weui 不能支持表单类型
export default function Button({
  text = '按钮',
  size = 'default',
  type = 'primary',
  contentSlot,
  formType,
  loading = false,
  disabled = false,
  events = {},
  className,
  style,
  id,
}) {
  const platform = usePlatform();
  const isH5 = platform === 'h5';
  const cls = classNames({
    'weda-ui': true,
    'weda-button': true,
    'weda-button-mini': size === 'mini',
    'weui-btn': isH5,
    'weui-btn_mini': isH5 && size === 'mini',
    'weui-btn_primary': isH5 && type === 'primary',
    'weui-btn_default': isH5 && type === 'default',
    'weui-btn_warn': isH5 && type === 'warn',
    'weui-btn_disabled': isH5 && disabled,
    [className]: className,
  });
  const onClick = (e) => events.tap({}, { originEvent: e });

  if(platform === 'h5') {
    return (
      <button
      className={cls}
      disabled={disabled}
      type={formType}
      style={style}
      id={id}
      onClick={onClick}
      >
      {loading && (
        <span className="weui-btn_loading">
          <i className="weui-loading" />
        </span>
      )}
      {text ? text : contentSlot}
    </button>
  );
}

let teaType = type;
if(teaType === 'warn') teaType = 'error';
return (
  <ConfigProvider classPrefix="wedatea2td">
    <TeaButton
      loading={loading} 
      onClick={onClick}
      disabled={disabled}
      htmlType={formType}
      type={teaType}
      style={style}
      className={cls}
      id={id}
      >
      {text ? text : contentSlot}
    </TeaButton>
  </ConfigProvider>
);
}

Button.propTypes = {
  /**
   * 内容
   */
  text: PropTypes.string,

  /**
   * 样式类型
   */
  type: PropTypes.oneOf(['primary', 'warn', 'default']),

  /**
   * 大小
   */
  size: PropTypes.oneOf(['default', 'mini']),

  /**
   * 是否禁用
   */
  disabled: PropTypes.bool,

  /**
   * 加载中
   */
  loading: PropTypes.bool,

  /**
   * 组件事件
   */
  events: PropTypes.objectOf(PropTypes.func),

  /**
   * 用于 form 类型
   */
  formType: PropTypes.oneOf(['button', 'submit', 'reset']),

  className: PropTypes.string,
  contentSlot: PropTypes.string,
  style: PropTypes.object,
  id: PropTypes.string,
};

/**
 * 默认属性
 */
Button.defaultProps = {
  type: 'primary',
  size: 'default',
};
