import React, { forwardRef } from 'react';
import { clsx } from 'clsx';
import { baseColors, statusColors } from '../../../styles/colors';

/**
 * ProgressBar component with global color system integration
 *
 * Supports both base color variants (with gradients) and status color variants (solid colors)
 * - Base variants: default, success, warning, danger, info (use gradients from color scales)
 * - Status variants: pending, inProgress, completed (use solid colors from statusColors)
 */
export interface ProgressBarProps {
  value: number;
  max?: number;
  size?: 'sm' | 'md' | 'lg';
  variant?: 'default' | 'success' | 'warning' | 'danger' | 'info' | 'pending' | 'inProgress' | 'completed' | 'indeterminate';
  showLabel?: boolean;
  label?: string;
  className?: string;
  animated?: boolean;
  customColor?: string;
  glow?: boolean;
}

const ProgressBar = forwardRef<HTMLDivElement, ProgressBarProps>(({
  value,
  max = 100,
  size = 'md',
  variant = 'default',
  showLabel = false,
  label,
  className,
  animated = false,
  customColor,
  glow = false,
  ...props
}, ref) => {
  const percentage = Math.min(Math.max((value / max) * 100, 0), 100);
  const isIndeterminate = variant === 'indeterminate';

  const sizeClasses = {
    sm: 'h-2',
    md: 'h-3',
    lg: 'h-4',
  };

  const getVariantStyle = (variant: string) => {
    // Map base color variants
    const baseColorMap = {
      default: baseColors.primary,
      success: baseColors.success,
      warning: baseColors.warning,
      danger: baseColors.error,
      info: baseColors.info,
    };

    // Map status color variants (these use single colors from statusColors)
    const statusColorMap = {
      pending: statusColors.pending.primary,
      inProgress: statusColors.inProgress.primary,
      completed: statusColors.completed.primary,
    };

    // Check if it's a base color variant (has color scales)
    if (variant in baseColorMap) {
      const colors = baseColorMap[variant as keyof typeof baseColorMap];
      // Enhanced gradient with multiple color stops for a more modern look
      return {
        background: `linear-gradient(90deg, ${colors[300]}, ${colors[400]}, ${colors[500]}, ${colors[600]})`,
        backgroundSize: '200% 100%',
        animation: animated ? 'gradient-shift 2s ease infinite' : undefined,
      };
    }

    // Check if it's a status color variant (single color)
    if (variant in statusColorMap) {
      const color = statusColorMap[variant as keyof typeof statusColorMap];
      return {
        backgroundColor: color,
      };
    }

    // Default fallback
    return {
      background: `linear-gradient(90deg, ${baseColors.primary[300]}, ${baseColors.primary[400]}, ${baseColors.primary[500]}, ${baseColors.primary[600]})`,
      backgroundSize: '200% 100%',
      animation: animated ? 'gradient-shift 2s ease infinite' : undefined,
    };
  };

  // Determine if we should show animation
  const shouldAnimate = animated && percentage < 100 && !isIndeterminate;

  return (
    <div 
      ref={ref} 
      className={clsx('w-full', className)} 
      role="progressbar"
      aria-valuenow={isIndeterminate ? undefined : value}
      aria-valuemin={isIndeterminate ? undefined : 0}
      aria-valuemax={isIndeterminate ? undefined : max}
      aria-label={label || (isIndeterminate ? "Loading" : `${Math.round(percentage)}% complete`)}
      {...props}
    >
      {(showLabel || label) && !isIndeterminate && (
        <div className="flex justify-between items-center mb-1">
          <span className="text-sm font-medium text-[var(--text-primary)]">
            {label || `${value}/${max}`}
          </span>
          <span className="text-sm text-[var(--text-secondary)]">
            {Math.round(percentage)}%
          </span>
        </div>
      )}
      <div 
        className={clsx(
          'w-full bg-[var(--bg-quaternary)] rounded-full overflow-hidden',
          sizeClasses[size],
          {
            'animate-pulse': isIndeterminate,
          }
        )}
      >
        <div
          className={clsx(
            'h-full rounded-full transition-all duration-500 ease-out relative overflow-hidden',
            {
              'animate-progress-indeterminate': isIndeterminate,
              'shadow-sm': glow && !isIndeterminate,
            }
          )}
          style={{
            width: isIndeterminate ? '100%' : `${percentage}%`,
            ...(customColor ? { backgroundColor: customColor } : getVariantStyle(variant)),
            ...(glow && !isIndeterminate ? { 
              boxShadow: `0 0 8px ${customColor || (variant in statusColors ? statusColors[variant as keyof typeof statusColors]?.primary : baseColors[variant as keyof typeof baseColors]?.[500] || baseColors.primary[500])}` 
            } : {})
          }}
        >
          {/* Animated shimmer effect for active progress */}
          {shouldAnimate && (
            <div
              className="absolute inset-0 opacity-30"
              style={{
                background: 'linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.4), transparent)',
                animation: 'progress-indeterminate 2s ease infinite',
              }}
            />
          )}
          
          {/* Enhanced indeterminate animation */}
          {isIndeterminate && (
            <div
              className="absolute inset-0 opacity-40"
              style={{
                background: 'linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.6), transparent)',
                animation: 'progress-indeterminate 1.5s ease infinite',
              }}
            />
          )}
        </div>
      </div>
    </div>
  );
});

ProgressBar.displayName = 'ProgressBar';

export default ProgressBar;