import PropTypes from 'prop-types';
import isUndefined from 'lodash/isUndefined';

import Button from '../Button';
import { mergeProps } from '../Util';
import { withDeprecated } from '../Util/deprecate';

/**
 * Action button component
 * @typedef {{
 *  href: string;
 *  children?: import('react').ReactNode;
 *  gradient?: string;
 *  color?: string;
 *  icon?: string;
 *  border?: string;
 *  text?: string;
 *  theme?: string;
 *  variant?: string;
 *  size?: string;
 *  width?: string;
 * }} ActionButtonProps
 */

/**
 * Action button component
 * @param {ActionButtonProps} props
 * @returns {JSX.Element}
 */
function ActionButton({ ...rawProps }) {
  const props = Object.assign({}, rawProps);
  if (isUndefined(props.gradient)) {
    props.gradient = '';
  }
  if (isUndefined(props.icon)) {
    props.icon = '';
  }
  if (isUndefined(props.text)) {
    props.text = '';
  }
  if (isUndefined(props.color)) {
    props.color = '';
  }
  if (isUndefined(props.border)) {
    props.border = '';
  }
  if (isUndefined(props.width)) {
    props.width = '';
  }
  if (isUndefined(props.theme)) {
    props.theme = 'inherit';
  }
  if (isUndefined(props.variant)) {
    props.variant = 'outlined';
  }
  if (isUndefined(props.size)) {
    props.size = 'large';
  }
  /** @type {ActionButtonProps & {}} */
  const newProps = mergeProps(props, ActionButton);
  const { href, icon, size, color, theme, variant, gradient, children, text, ...rest } = newProps;

  /** @type {import('react').CSSProperties} */
  const styles = {};
  if (gradient) {
    styles.backgroundImage = gradient;
    styles.borderColor = 'transparent';
  }
  const attrs = ['color', 'border', 'width'];
  attrs.forEach((x) => {
    if (newProps[x]) {
      styles[x] = newProps[x];
    }
  });

  return (
    <Button
      color={theme}
      href={href}
      target="_blank"
      variant={variant}
      style={styles}
      size={size}
      className="action-button"
      {...rest}>
      {!!icon && <i className={icon} />}
      {text || children}
    </Button>
  );
}

ActionButton.propTypes = {
  href: PropTypes.string.isRequired,
  children: PropTypes.any,
  gradient: PropTypes.string,
  color: PropTypes.string,
  icon: PropTypes.string,
  border: PropTypes.string,
  text: PropTypes.string,
  theme: PropTypes.string,
  variant: PropTypes.string,
  size: PropTypes.string,
  width: PropTypes.string,
};

export default withDeprecated(ActionButton, { name: 'ActionButton' });
