/**
 * button组件
 * TODO: 完善props
 */
import classNames from 'classnames'
import React, { FC, useEffect } from 'react'
import { tuple } from '../_util/common'
import { ConfigConsumer } from '../provider'
import './style/index.css'

const ButtonTypes = tuple('default', 'primary', 'dashed', 'danger')
export type ButtonType = typeof ButtonTypes[number]
const ButtonSizes = tuple('large', 'default', 'small')
export type ButtonSize = typeof ButtonSizes[number]
const ButtonHTMLTypes = tuple('submit', 'button', 'reset')
export type ButtonHTMLType = typeof ButtonHTMLTypes[number]

export interface ButtonProps
  extends Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, 'type'> {
  htmlType?: React.ButtonHTMLAttributes<HTMLButtonElement>['type']
  type?: ButtonType
  size?: ButtonSize
  loading?: boolean
  block?: boolean
}

const Button: FC<ButtonProps> = props => {
  const {
    type,
    loading,
    size,
    children,
    block,
    onClick,
    htmlType,
    ...other
  } = props

  const handleClick: React.MouseEventHandler<HTMLButtonElement> = e => {
    if (!!loading) return
    if (onClick) onClick(e)
  }

  useEffect(() => {
    if (loading) {
      // tslint:disable-next-line: return-undefined
      return
    }
  }, [loading])

  const renderButton = () => {
    let sizeCls = ''
    switch (size) {
      case 'large':
        sizeCls = 'lg'
        break
      case 'small':
        sizeCls = 'sm'
      // tslint:disable-next-line: no-switch-case-fall-through
      default:
        break
    }

    const classes = classNames('btn', {
      [`btn-${type}`]: type,
      [`btn-${sizeCls}`]: sizeCls,
      [`btn-block`]: block,
    })

    return (
      <button
        className={classes}
        onClick={handleClick}
        type={htmlType}
        {...other}
      >
        {children}
      </button>
    )
  }
  return <ConfigConsumer>{renderButton}</ConfigConsumer>
}

export default Button
