import React, { useRef, useState } from 'react';

type ButtonVariant = 'primary' | 'secondary' | 'outline' | 'danger' | 'ghost';
type ButtonSize = 'sm' | 'md' | 'lg';

type ButtonClickHandler = (
  event: React.MouseEvent<HTMLButtonElement>,
) => void | Promise<void>;

interface ButtonProps extends Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, 'onClick'> {
  variant?: ButtonVariant;
  size?: ButtonSize;
  /** External loading (e.g. form-level busy). ORed with auto-pending from async onClick. */
  isLoading?: boolean;
  fullWidth?: boolean;
  children: React.ReactNode;
  /**
   * If the handler returns a Promise, the button stays loading/disabled until it
   * settles — prevents double-clicks without a separate busy flag per call site.
   * Prefer `onClick={() => doThing()}` over `onClick={() => void doThing()}`.
   */
  onClick?: ButtonClickHandler;
}

export const Button: React.FC<ButtonProps> = ({
  variant = 'primary',
  size = 'md',
  isLoading = false,
  fullWidth = false,
  children,
  className = '',
  disabled,
  onClick,
  ...props
}) => {
  const [autoPending, setAutoPending] = useState(false);
  const autoPendingRef = useRef(false);

  const pending = isLoading || autoPending;

  const baseClasses =
    'inline-flex items-center justify-center rounded-[var(--radius-md)] font-medium transition-all duration-200 ' +
    'focus:outline-none focus:ring-2 focus:ring-primary/40 disabled:cursor-not-allowed';

  const variantClasses: Record<ButtonVariant, string> = {
    primary: 'bg-primary text-white hover:opacity-90 disabled:opacity-60',

    secondary:
      'bg-surface-elevated text-text-primary border border-border hover:border-border-strong disabled:opacity-50',

    outline:
      'border border-border text-text-primary hover:bg-background-card/70 disabled:opacity-50',

    danger: 'bg-red-600 text-white hover:bg-red-700 disabled:opacity-50',

    ghost:
      'text-text-secondary hover:text-text-primary hover:bg-background-card/70 disabled:opacity-50',
  };

  const sizeClasses: Record<ButtonSize, string> = {
    sm: 'px-3 py-1.5 text-sm',
    md: 'px-4 py-2 text-sm',
    lg: 'px-6 py-3 text-base',
  };

  const widthClass = fullWidth ? 'w-full' : '';
  const loadingClass = pending ? 'opacity-70 animate-pulse pointer-events-none' : '';

  const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
    if (disabled || pending || autoPendingRef.current) {
      event.preventDefault();
      return;
    }
    if (!onClick) return;

    const result = onClick(event);
    if (result != null && typeof (result as Promise<void>).then === 'function') {
      autoPendingRef.current = true;
      setAutoPending(true);
      void Promise.resolve(result).finally(() => {
        autoPendingRef.current = false;
        setAutoPending(false);
      });
    }
  };

  return (
    <button
      type="button"
      {...props}
      className={`${baseClasses} ${variantClasses[variant]} ${sizeClasses[size]} ${widthClass} ${loadingClass} ${className}`}
      disabled={disabled || pending}
      aria-busy={pending || undefined}
      onClick={handleClick}
    >
      {children}
    </button>
  );
};
