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

export interface CountBadgeProps extends Omit<HTMLAttributes<HTMLSpanElement>, 'children'> {
  /**
   * The count to display
   */
  count: number;

  /**
   * Maximum count to display before showing "99+"
   * @default 99
   */
  max?: number;

  /**
   * Whether to show zero counts
   * @default false
   */
  showZero?: boolean;

  /**
   * Visual style variant
   * @default 'error'
   */
  variant?: 'primary' | 'secondary' | 'success' | 'warning' | 'error' | 'info';

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

  /**
   * Position offset when used as overlay [x, y]
   * @example [4, -4] moves badge 4px right and 4px up
   */
  offset?: [number, number];

  /**
   * Whether this badge is positioned as an overlay
   * @default false
   */
  overlay?: boolean;
}

/**
 * CountBadge - Displays numerical counts, typically for notifications
 *
 * Features:
 * - Automatic max count display (99+)
 * - Optional zero count hiding
 * - Overlay mode for positioning over other elements
 * - Multiple semantic variants
 * - Responsive sizing
 * - Accessible with proper ARIA labels
 *
 * @example
 * ```tsx
 * // Standalone count badge
 * <CountBadge count={5} />
 *
 * // As overlay on an icon
 * <div className="relative">
 *   <Bell />
 *   <CountBadge count={12} overlay />
 * </div>
 *
 * // With custom positioning
 * <CountBadge count={99} overlay offset={[2, -2]} />
 * ```
 */
export const CountBadge = forwardRef<HTMLSpanElement, CountBadgeProps>(({
  count,
  max = 99,
  showZero = false,
  variant = 'error',
  size = 'md',
  offset,
  overlay = false,
  className,
  style,
  ...props
}, ref) => {
  // Don't render if count is 0 and showZero is false
  if (count === 0 && !showZero) {
    return null;
  }

  // Format the display count
  const displayCount = count > max ? `${max}+` : count.toString();

  // Base classes for all count badges
  const baseClasses = [
    'inline-flex items-center justify-center',
    'font-semibold tabular-nums',
    'whitespace-nowrap',
    'rounded-full',
    'transition-all duration-200 ease-in-out',
  ];

  // Overlay-specific classes
  const overlayClasses = overlay ? [
    'absolute',
    'ring-2 ring-[var(--bg-primary)]',
  ] : [];

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

  // Size-specific classes
  const sizeClasses = {
    sm: [
      'min-w-4 h-4',
      'text-xs',
      'px-1',
    ],
    md: [
      'min-w-5 h-5',
      'text-xs',
      'px-1.5',
    ],
    lg: [
      'min-w-6 h-6',
      'text-sm',
      'px-2',
    ],
  };

  // Overlay positioning classes
  const overlayPositionClasses = overlay ? [
    '-top-1',
    '-right-1',
  ] : [];

  const classes = clsx(
    baseClasses,
    overlayClasses,
    variantClasses[variant],
    sizeClasses[size],
    overlayPositionClasses,
    className
  );

  // Calculate offset style if provided
  const offsetStyle = offset && overlay ? {
    transform: `translate(${offset[0]}px, ${offset[1]}px)`,
  } : undefined;

  return (
    <span
      ref={ref}
      className={classes}
      style={{
        ...style,
        ...offsetStyle,
      }}
      role="status"
      aria-label={`${count} notification${count !== 1 ? 's' : ''}`}
      {...props}
    >
      {displayCount}
    </span>
  );
});

CountBadge.displayName = 'CountBadge';

export default CountBadge;
