import { cn } from '../../lib/utils';
import React from 'react';

type ProgressBarSize = 'xs' | 'sm' | 'md';

export interface ProgressBarProps {
  value?: number;
  progress?: number;
  label?: string;
  sublabel?: string;
  showValue?: boolean;
  showPercent?: boolean;
  size?: ProgressBarSize;
  color?: 'primary' | 'emerald' | 'amber' | 'indigo';
  animated?: boolean;
  className?: string;
  'aria-label'?: string;
}

const SIZE_HEIGHT: Record<ProgressBarSize, string> = {
  xs: 'h-1',
  sm: 'h-2',
  md: 'h-3',
};

export function ProgressBar({
  value,
  progress,
  label,
  sublabel,
  showValue = false,
  showPercent = false,
  size = 'md',
  className,
  'aria-label': ariaLabelProp,
}: ProgressBarProps) {
  const rawValue = value !== undefined ? value : progress !== undefined ? progress : 0;
  const numeric = Number.isFinite(rawValue) ? rawValue : 0;
  const clamped = Math.max(0, Math.min(100, Math.floor(numeric)));
  const resolvedAriaLabel = ariaLabelProp ?? label ?? 'Progress';
  const shouldShowValue = showValue || showPercent;
  const showHeader = Boolean(label) || shouldShowValue;

  return (
    <div className={cn('w-full', className)}>
      {showHeader && (
        <div className="mb-1 flex items-center justify-between gap-2">
          {label && (
            <span className="text-xs font-bold text-text-muted">{label}</span>
          )}
          {shouldShowValue && (
            <span className="text-xs font-bold tabular-nums text-text-muted">
              {clamped}%
            </span>
          )}
        </div>
      )}
      <div
        role="progressbar"
        aria-label={resolvedAriaLabel}
        aria-valuemin={0}
        aria-valuemax={100}
        aria-valuenow={clamped}
        className={cn(
          'w-full overflow-hidden rounded-full border border-border bg-muted',
          SIZE_HEIGHT[size],
        )}
      >
        <div
          className="h-full bg-primary transition-[width] duration-200 ease-out"
          style={{ width: `${clamped}%` }}
        />
      </div>
      {sublabel && (
        <p className="text-[0.65rem] text-text-muted font-medium truncate mt-1">{sublabel}</p>
      )}
    </div>
  );
}

export default ProgressBar;
