import {useState, useEffect, CSSProperties} from 'react';
import * as React from 'react';
// If I don't call react this way,
// Jest will say 'Cannot read property 'createElement' of undefined'

import sc from 'utils/classname';
import Icon from 'lib/icon/icon';
import './index.scss';

interface ButtonProps {
  type?: 'primary' | 'danger' | 'warning' | 'success' | 'midnightBlue' | 'dark',
  loading?: boolean,
  className?: string,
  style?: CSSProperties,
  onClick?: React.MouseEventHandler
}

const Button: React.FunctionComponent<ButtonProps> = (props) => {
  const [position, setPosition] = useState({
    left: 0,
    top: 0
  });
  const [e, setE] = useState<EventTarget & Element | null>(null);
  const {onClick, className, type, loading, ...restProps} = props;

  const btnClasses = sc(className, 'wen-button', type, loading ? 'wen-loading' : '');

  // add animation for click event
  const onClickWithAnimation = (e: React.MouseEvent) => {
    if (loading) {
      return;
    }

    setE(e.currentTarget);
    setPosition(getWavePosition(e));

    if (typeof onClick === 'function') {
      onClick.call(e.target, e);
    }
  };

  const getWavePosition = (e: React.MouseEvent) => {
    if (e && e.currentTarget) {
      if (e.currentTarget.getBoundingClientRect) {
        const {left, top} = e.currentTarget.getBoundingClientRect();
        return {
          left: e.clientX - left,
          top: e.clientY - top
        }
      }
    }
    return {
      left: 0,
      top: 0
    }
  };

  const iconWrapper = loading ?
    (
      <div className="wen-loading-icon-wrapper">
        <Icon name="loading" className="wen-loading-icon"/>
      </div>
    )
    :
    '';

  useEffect(() => {
    if (!e) return;
    e.classList.add('wen-wave');
    e.addEventListener('transitionend', () => {
      e.classList.remove('wen-wave');
    })
  });

  return (
    <button className={btnClasses} onClick={onClickWithAnimation} {...restProps}>
      {iconWrapper}
      <span className="wen-button-inner">
        {props.children}
      </span>
      <span className="wen-wave-dot" style={position}/>
    </button>
  );
};

Button.defaultProps = {
  loading: false,
};

export default Button;