import type { HTMLAttributes, ReactNode } from 'react';
import { useId, useMemo } from 'react';
import type { ProgressColor } from '../types';
import './progress.css';

export type ProgressSize = 'sm' | 'md' | 'lg' | 'xl';

export type ProgressBarProps = {
  value: number;
  max?: number;
  color?: ProgressColor;
  size?: ProgressSize;
  striped?: boolean;
  animatedStripes?: boolean;
  /** Animates width from 0 → value on mount. */
  animated?: boolean;
  label?: ReactNode;
  showLabel?: boolean;
  ariaLabel?: string;
} & Omit<HTMLAttributes<HTMLDivElement>, 'children'>;

function clamp(n: number, min: number, max: number) {
  return Math.min(max, Math.max(min, n));
}

export function ProgressBar({
  value,
  max = 100,
  color = 'primary',
  size = 'md',
  striped = false,
  animatedStripes = false,
  animated = false,
  label,
  showLabel = false,
  ariaLabel,
  className,
  ...rest
}: ProgressBarProps) {
  const id = useId().replace(/:/g, '');
  const percent = useMemo(() => {
    if (!Number.isFinite(value) || !Number.isFinite(max) || max <= 0) return 0;
    return clamp((value / max) * 100, 0, 100);
  }, [max, value]);

  const text = useMemo(() => {
    if (label != null) return label;
    if (!showLabel) return null;
    return `${Math.round(percent)}%`;
  }, [label, percent, showLabel]);

  return (
    <div
      id={`ccl-progress-${id}`}
      className={['ccl-progress', `ccl-progress--${size}`, className ?? ''].filter(Boolean).join(' ')}
      role="progressbar"
      aria-label={ariaLabel}
      aria-valuemin={0}
      aria-valuemax={max}
      aria-valuenow={value}
      {...rest}
    >
      <div
        className={[
          'ccl-progress__bar',
          `ccl-progress__bar--${color}`,
          striped ? 'ccl-progress__bar--striped' : '',
          striped && animatedStripes ? 'ccl-progress__bar--striped-animated' : '',
          animated ? 'ccl-progress__bar--animated' : '',
        ]
          .filter(Boolean)
          .join(' ')}
        style={{ ['--ccl-progress-value' as never]: `${percent}%` } as React.CSSProperties}
      >
        {text ? <span className="ccl-progress__label">{text}</span> : null}
      </div>
    </div>
  );
}

