import React from 'react';
import { ButtonWithIconProps } from './ButtonTypes';

interface ButtonProps extends ButtonWithIconProps {
  as?: 'button' | 'a';
  href?: string;
}

const Button: React.FC<ButtonProps> = ({
  variant = 'primary',
  size = 'md',
  disabled = false,
  loading = false,
  className = '',
  children,
  onClick,
  type = 'button',
  icon: Icon,
  iconPosition = 'left',
  as: Component = 'button',
  href,
  ...props
}) => {
  // Build CSS classes using global styles
  const baseClasses = [
    'button',
    `button${variant.charAt(0).toUpperCase() + variant.slice(1)}`,
    `button${size.charAt(0).toUpperCase() + size.slice(1)}`,
    loading ? 'loading' : '',
    className
  ].filter(Boolean).join(' ');

  // Handle click
  const handleClick = (e: React.MouseEvent<HTMLButtonElement | HTMLAnchorElement>) => {
    if (!disabled && !loading && onClick) {
      e.preventDefault();
      onClick();
    }
  };

  // Render icon
  const renderIcon = () => {
    if (!Icon) return null;
    
    return (
      <Icon 
        className={`buttonIcon ${
          iconPosition === 'left' ? 'buttonIconLeft' : 'buttonIconRight'
        }`} 
      />
    );
  };

  // Render loading spinner
  const renderSpinner = () => {
    if (!loading) return null;
    return <div className="buttonSpinner" />;
  };

  // Common props
  const commonProps = {
    className: baseClasses,
    onClick: handleClick,
    disabled: disabled || loading,
    ...props
  };

  // Render as anchor
  if (Component === 'a') {
    return (
      <a href={href} {...commonProps}>
        {renderSpinner()}
        {renderIcon()}
        {children}
      </a>
    );
  }

  // Render as button
  return (
    <button type={type} {...commonProps}>
      {renderSpinner()}
      {renderIcon()}
      {children}
    </button>
  );
};

export default Button;
