import React from 'react';

export type BadgeVariant = 'success' | 'warning' | 'danger' | 'default';

interface BadgeProps {
  children: React.ReactNode;
  variant?: BadgeVariant;
  className?: string;
  /**
   * Same pixel width for every badge (table columns).
   * Set false only when the pill should shrink to the label.
   */
  fixedWidth?: boolean;
  /**
   * Inline style overriding the variant colors — e.g. dynamic prosthesis-type
   * pastels via `prosthesisTypeBadgeStyle(code)`. Wins over variant classes.
   */
  style?: React.CSSProperties;
  /** Native tooltip, useful when the label may be truncated. */
  title?: string;
  /** Clip an over-long label with an ellipsis instead of wrapping/overflowing. */
  truncate?: boolean;
}

const variantStyles: Record<BadgeVariant, string> = {
  success: 'bg-badge-success-bg text-badge-success-fg border-badge-success-border',
  warning: 'bg-badge-warning-bg text-badge-warning-fg border-badge-warning-border',
  danger: 'bg-badge-danger-bg text-badge-danger-fg border-badge-danger-border',
  default: 'bg-badge-default-bg text-badge-default-fg border-badge-default-border',
};

/** Explicit width + height so every row matches; flex centers label optically. */
const FIXED_LAYOUT_CLASS =
  'w-[8rem] min-w-[8rem] max-w-[8rem] shrink-0 h-7 px-2 py-0';

export function Badge({
  children,
  variant = 'default',
  className,
  fixedWidth = true,
  style,
  title,
  truncate = false,
}: BadgeProps) {
  const layoutClass = fixedWidth
    ? `${FIXED_LAYOUT_CLASS} justify-center text-center`
    : 'min-h-[1.75rem] px-2.5 py-1 justify-center';
  const wrapClass = truncate ? '' : 'whitespace-nowrap';

  return (
    <span
      className={`inline-flex items-center box-border rounded-md border text-xs font-medium leading-none ${wrapClass} ${variantStyles[variant]} ${layoutClass} ${className ?? ''}`}
      style={style}
      title={title}
    >
      {truncate ? <span className="w-full truncate text-center">{children}</span> : children}
    </span>
  );
}
