import React, { memo, useCallback, useState, useEffect } from 'react'
import { Button, Input, Cascader } from 'antd';
import classNames from 'classnames'

import './style.less'

/**
 * @param {string} btnText 按钮文本: 非空时显示按钮
 * @param {function} onBtnClick 按钮点击事件
 */
export default memo(function EpyInput(props) {
  const {
    label = '',
    labelWidth = 100,
    btnText = '',
    btnWidth = 100,
    btnLoading = false,
    btnDisabled = false,
    size = 'middle',
    type = 'text',
    validateStatus = 'success',
    help = '',
    value: defaultValue,
    require,
    onBtnClick,
    ...otherProps
  } = props;

  const [isFocusing, setIsFocusing] = useState(false)

  const className = classNames({
    'epy-input': true,
    [props.className]: !!props.className,
    ['epy-input-' + size]: true,
    ['epy-input-' + validateStatus]: true,
    'epy-input-focus': isFocusing,
  })

  const handleFocus = useCallback((...args) => {
    setIsFocusing(true)
    props.onFocus && props.onFocus(...args)
  }, [props.onFocus])

  const handleBlur = useCallback((...args) => {
    setIsFocusing(false)
    props.onBlur && props.onBlur(...args)
  }, [props.onBlur])

  const handleBtnClick = useCallback((...args) => {
    onBtnClick && onBtnClick(...args)
  }, [onBtnClick])

  return (
    <div className={className}>
      <label className={"label" + (require ? ' require' : '')} style={{ width: labelWidth }}>{label}</label>
      {
        type !== 'cascader' && type !== 'password' &&
        <>
          <Input {...otherProps} type={type} defaultValue={defaultValue} className="input" onFocus={handleFocus} onBlur={handleBlur} />
          {
            btnText &&
            <>
              <span className="btn-placeholder" style={{ width: btnWidth }}></span>
              <Button type="text" className="button" loading={btnLoading} disabled={btnDisabled} style={{ width: btnWidth }} onClick={handleBtnClick}>{btnText}</Button>
            </>
          }
        </>
      }
      {
        type === 'password' &&
        <Input.Password {...otherProps} defaultValue={defaultValue} className="input" onFocus={handleFocus} onBlur={handleBlur} />
      }
      {
        type === 'cascader' &&
        <Cascader {...otherProps} defaultValue={defaultValue} className="cascader" onFocus={handleFocus} onBlur={handleBlur} />
      }
      <p className="tips" style={{ left: 10 }}>{help}</p>
    </div>
  )
})
