import { Loader2 } from 'lucide-react';
import React, { MouseEventHandler, ReactNode, forwardRef } from 'react';
import { Box } from './Box';
import { Icon } from './Icon';

export interface ButtonProps {
  children: ReactNode;
  onClick?: MouseEventHandler<HTMLButtonElement | HTMLAnchorElement>;
  variant?: 'primary' | 'secondary' | 'danger' | 'ghost' | 'success' | 'discord' | 'race-final';
  size?: 'sm' | 'md' | 'lg';
  disabled?: boolean;
  isLoading?: boolean;
  type?: 'button' | 'submit' | 'reset';
  icon?: ReactNode;
  fullWidth?: boolean;
  as?: 'button' | 'a';
  href?: string;
  target?: string;
  rel?: string;
  title?: string;
  style?: React.CSSProperties;
  rounded?: boolean | string;
  className?: string;
  bg?: string;
  color?: string;
  w?: string | number;
  h?: string | number;
  px?: number;
  borderColor?: string;
  mt?: number;
  position?: 'static' | 'relative' | 'absolute' | 'fixed' | 'sticky';
  letterSpacing?: string;
  hoverBorderColor?: string;
  fontSize?: string;
  p?: number;
  minHeight?: string;
  transition?: boolean;
  ring?: string;
  transform?: string;
  hoverScale?: boolean;
  overflow?: string;
  borderWidth?: string;
  aspectRatio?: string;
  border?: boolean;
  shadow?: string;
  display?: string;
  center?: boolean;
}

export const Button = forwardRef<HTMLButtonElement | HTMLAnchorElement, ButtonProps>(({ 
  children, 
  onClick, 
  variant = 'primary',
  size = 'md',
  disabled = false,
  isLoading = false,
  type = 'button',
  icon,
  fullWidth = false,
  as = 'button',
  href,
  target,
  rel,
  title,
  style: styleProp,
  rounded = false,
  className,
  bg,
  color,
  w,
  h,
  px,
  borderColor,
  mt,
  position,
  letterSpacing,
  hoverBorderColor,
  fontSize,
  p,
  minHeight,
  transition,
  ring,
  transform,
  hoverScale,
  overflow,
  borderWidth,
  aspectRatio,
  border,
  shadow,
  display,
  center,
}, ref) => {
  const baseClasses = 'inline-flex items-center justify-center focus-visible:outline focus-visible:outline-1 focus-visible:outline-offset-2 active:opacity-80 uppercase tracking-widest font-bold';
  const transitionClasses = transition !== false ? 'transition-all duration-150 ease-in-out' : '';
  
  const variantClasses = {
    primary: 'bg-[var(--ui-color-intent-primary)] text-white hover:opacity-90 focus-visible:outline-[var(--ui-color-intent-primary)] shadow-[0_0_15px_rgba(25,140,255,0.3)] hover:shadow-[0_0_25px_rgba(25,140,255,0.5)]',
    secondary: 'bg-[var(--ui-color-bg-surface)] text-white border border-[var(--ui-color-border-default)] hover:bg-[var(--ui-color-border-default)] focus-visible:outline-[var(--ui-color-intent-primary)]',
    danger: 'bg-[var(--ui-color-intent-critical)] text-white hover:opacity-90 focus-visible:outline-[var(--ui-color-intent-critical)]',
    ghost: 'bg-transparent text-[var(--ui-color-text-low)] hover:text-[var(--ui-color-text-high)] hover:bg-white/5 focus-visible:outline-[var(--ui-color-text-low)]',
    success: 'bg-[var(--ui-color-intent-success)] text-[var(--ui-color-bg-base)] hover:opacity-90 focus-visible:outline-[var(--ui-color-intent-success)]',
    'race-final': 'bg-[var(--ui-color-intent-success)] text-[var(--ui-color-bg-base)] hover:opacity-90 focus-visible:outline-[var(--ui-color-intent-success)]',
    discord: 'bg-[#5865F2] text-white hover:bg-[#4752C4] focus-visible:outline-[#5865F2]',
  };
  
  const sizeClasses = {
    sm: 'min-h-[32px] px-3 py-1 text-xs',
    md: 'min-h-[40px] px-4 py-2 text-sm',
    lg: 'min-h-[48px] px-6 py-3 text-base'
  };
  
  const disabledClasses = (disabled || isLoading) ? 'opacity-40 cursor-not-allowed' : 'cursor-pointer';
  const widthClasses = fullWidth ? 'w-full' : '';
  const roundedClasses = rounded === true ? 'rounded-full' : (typeof rounded === 'string' ? `rounded-${rounded}` : 'rounded-none');
  
  const classes = [
    baseClasses,
    transitionClasses,
    variantClasses[variant],
    sizeClasses[size],
    disabledClasses,
    widthClasses,
    roundedClasses,
    ring,
    hoverScale ? 'hover:scale-105' : '',
    display === 'flex' ? 'flex' : '',
    center ? 'items-center justify-center' : '',
    className,
  ].filter(Boolean).join(' ');
  
  const style: React.CSSProperties = {
    ...styleProp,
    ...(bg ? { backgroundColor: bg.startsWith('bg-') ? undefined : bg } : {}),
    ...(color ? { color: color.startsWith('text-') ? undefined : color } : {}),
    ...(w ? { width: w } : {}),
    ...(h ? { height: h } : {}),
    ...(px ? { paddingLeft: `${px * 0.25}rem`, paddingRight: `${px * 0.25}rem` } : {}),
    ...(borderColor ? { borderColor: borderColor.startsWith('border-') ? undefined : borderColor, borderStyle: 'solid', borderWidth: '1px' } : {}),
    ...(mt ? { marginTop: `${mt * 0.25}rem` } : {}),
    ...(position ? { position } : {}),
    ...(letterSpacing ? { letterSpacing } : {}),
    ...(fontSize ? { fontSize } : {}),
    ...(p !== undefined ? { padding: `${p * 0.25}rem` } : {}),
    ...(minHeight ? { minHeight } : {}),
    ...(transform ? { transform } : {}),
    ...(overflow ? { overflow } : {}),
    ...(borderWidth ? { borderWidth } : {}),
    ...(aspectRatio ? { aspectRatio } : {}),
    ...(border ? { border: '1px solid var(--ui-color-border-default)' } : {}),
    ...(shadow ? { boxShadow: shadow.startsWith('shadow-') ? undefined : shadow } : {}),
  };

  const content = (
    <Box display="flex" alignItems="center" gap={2}>
      {isLoading && <Icon icon={Loader2} size={size === 'sm' ? 3 : 4} animate="spin" />}
      {!isLoading && icon}
      {children}
    </Box>
  );

  if (as === 'a') {
    return (
      <a
        ref={ref as React.ForwardedRef<HTMLAnchorElement>}
        href={href}
        target={target}
        rel={rel}
        className={classes}
        onClick={onClick as MouseEventHandler<HTMLAnchorElement>}
        style={style}
        title={title}
      >
        {content}
      </a>
    );
  }

  return (
    <button 
      ref={ref as React.ForwardedRef<HTMLButtonElement>}
      type={type}
      className={classes}
      onClick={onClick as MouseEventHandler<HTMLButtonElement>}
      disabled={disabled || isLoading}
      style={style}
      title={title}
    >
      {content}
    </button>
  );
});

Button.displayName = 'Button';
