import React, { forwardRef, HTMLAttributes } from 'react';
import { clsx } from 'clsx';

export interface BadgeProps extends HTMLAttributes<HTMLSpanElement> {
  /**
   * Visual style variant
   * @default 'default'
   */
  variant?: 'default' | 'primary' | 'secondary' | 'success' | 'warning' | 'error' | 'info' | 'outline';

  /**
   * Size variant
   * @default 'md'
   */
  size?: 'sm' | 'md' | 'lg';

  /**
   * Optional icon to display before the text
   */
  icon?: React.ReactNode;

  /**
   * Whether the badge is closable
   * @default false
   */
  closable?: boolean;

  /**
   * Callback when close button is clicked
   */
  onClose?: (e: React.MouseEvent<HTMLButtonElement>) => void;
}

/**
 * Badge - Simple label/tag component for displaying status, categories, or labels
 *
 * Features:
 * - Theme-aware with CSS custom properties
 * - Multiple semantic variants (success, warning, error, info)
 * - Three size options (sm, md, lg)
 * - Optional icon support
 * - Optional close button
 * - Accessible with proper ARIA labels
 *
 * @example
 * ```tsx
 * <Badge variant="success">Active</Badge>
 * <Badge variant="warning" icon={<AlertCircle />}>Warning</Badge>
 * <Badge variant="error" closable onClose={handleClose}>Error</Badge>
 * ```
 */
export const Badge = forwardRef<HTMLSpanElement, BadgeProps>(({
  variant = 'default',
  size = 'md',
  icon,
  closable = false,
  onClose,
  className,
  children,
  ...props
}, ref) => {
  // Base classes for all badges
  const baseClasses = [
    'inline-flex items-center justify-center',
    'font-medium whitespace-nowrap',
    'border',
    'transition-all duration-200 ease-in-out',
  ];

  // Variant-specific classes using CSS custom properties
  const variantClasses = {
    default: [
      'bg-[var(--bg-tertiary)]',
      'text-[var(--text-primary)]',
      'border-[var(--border-primary)]',
    ],
    primary: [
      'bg-[var(--color-primary)]',
      'text-white',
      'border-[var(--color-primary)]',
    ],
    secondary: [
      'bg-[var(--color-secondary)]',
      'text-white',
      'border-[var(--color-secondary)]',
    ],
    success: [
      'bg-[var(--color-success)]',
      'text-white',
      'border-[var(--color-success)]',
    ],
    warning: [
      'bg-[var(--color-warning)]',
      'text-white',
      'border-[var(--color-warning)]',
    ],
    error: [
      'bg-[var(--color-error)]',
      'text-white',
      'border-[var(--color-error)]',
    ],
    info: [
      'bg-[var(--color-info)]',
      'text-white',
      'border-[var(--color-info)]',
    ],
    outline: [
      'bg-transparent',
      'text-[var(--text-primary)]',
      'border-[var(--border-secondary)]',
    ],
  };

  // Size-specific classes
  const sizeClasses = {
    sm: [
      'px-2 py-0.5',
      'text-xs',
      'gap-1',
      'rounded-md',
      'min-h-5',
    ],
    md: [
      'px-3 py-1',
      'text-sm',
      'gap-1.5',
      'rounded-lg',
      'min-h-6',
    ],
    lg: [
      'px-4 py-1.5',
      'text-base',
      'gap-2',
      'rounded-lg',
      'min-h-8',
    ],
  };

  // Icon size based on badge size
  const iconSizeClasses = {
    sm: 'w-3 h-3',
    md: 'w-4 h-4',
    lg: 'w-5 h-5',
  };

  const classes = clsx(
    baseClasses,
    variantClasses[variant],
    sizeClasses[size],
    {
      'pr-1.5': closable && size === 'sm',
      'pr-2': closable && size === 'md',
      'pr-2.5': closable && size === 'lg',
    },
    className
  );

  return (
    <span
      ref={ref}
      className={classes}
      role="status"
      aria-label={typeof children === 'string' ? children : undefined}
      {...props}
    >
      {icon && (
        <span className={clsx('flex-shrink-0', iconSizeClasses[size])} aria-hidden="true">
          {icon}
        </span>
      )}

      <span className="flex-1">{children}</span>

      {closable && onClose && (
        <button
          type="button"
          onClick={onClose}
          className={clsx(
            'flex-shrink-0 ml-1',
            'rounded-full',
            'hover:bg-black/10 dark:hover:bg-white/10',
            'transition-colors duration-150',
            'focus:outline-none focus:ring-2 focus:ring-offset-1',
            'focus:ring-[var(--border-focus)]',
            {
              'p-0.5': size === 'sm',
              'p-1': size === 'md' || size === 'lg',
            }
          )}
          aria-label="Close"
        >
          <svg
            className={iconSizeClasses[size]}
            fill="none"
            strokeLinecap="round"
            strokeLinejoin="round"
            strokeWidth={2}
            viewBox="0 0 24 24"
            stroke="currentColor"
          >
            <path d="M6 18L18 6M6 6l12 12" />
          </svg>
        </button>
      )}
    </span>
  );
});

Badge.displayName = 'Badge';

export default Badge;
