import * as React from 'react';
import classnames from 'classnames';
import { CnBalloon } from '@alife/cn-ui';
import { ButtonProps } from 'src/types/op-button';
import { LoadingIcon } from '../common-view';
import event from '../event';

import './index.scss';

export default function Button(props: ButtonProps) {
  const {
    children,
    hotkey,
    className,
    type = 'normal',
    text = false,
    size = 'medium',
    disabled = false,
    loading = false,
    onClick = () => {},
    hotkeyHandler,
    style,
    balloon = {},
    fullWidth,
  } = props;

  React.useEffect(() => {
    const bindHandler = () => {
      if (hotkeyHandler instanceof Function) {
        hotkeyHandler();
      } else if (onClick instanceof Function) {
        onClick();
      }
    };
    if (hotkey && hotkey?.toLowerCase) {
      event.bind(hotkey.toLowerCase(), bindHandler);
    }
    return () => {
      if (hotkey && hotkey?.toLowerCase) {
        event.unbind(hotkey.toLowerCase(), bindHandler);
      }
    };
  }, [onClick, hotkeyHandler, hotkey]);

  const btn = (
    <button
      data-hottag='cn-op.button'
      type='button'
      className={classnames('op-btn', className, {
        'op-btn-normal': type === 'normal',
        'op-btn-primary': type === 'primary',
        'op-btn-secondary': type === 'secondary',
        'op-btn-error': type === 'error',
        'op-btn-text': type === 'text' || text,
        'op-btn-link': type === 'link',
        'op-btn-medium': size === 'medium',
        'op-btn-small': size === 'small',
        'op-btn-loading': loading,
        'op-btn-fullWidth': fullWidth,
      })}
      disabled={disabled}
      onClick={(e) => {
        e.stopPropagation();
        onClick();
      }}
      style={style}
    >
      <span className='op-btn-helper'>
        {loading ? <LoadingIcon /> : null}
        {children}
      </span>
      {hotkey ? <span className='op-btn-hotkey'>[{hotkey}]</span> : null}
    </button>
  );

  const { children: balloonChildren, ...rest } = balloon;
  return balloonChildren ? (
    <CnBalloon
      v2
      className='op-balloon'
      triggerType='hover'
      align='t'
      closable={false}
      trigger={btn}
      {...rest}
    >
      {balloonChildren}
    </CnBalloon>
  ) : (
    btn
  );
}
