import { cn } from '@/lib/utils'
import { useEffect, useState } from 'react'

interface ProgressIndicatorProps {
  currentStep: number
  totalSteps?: number
  className?: string
}

export default function ProgressIndicator({
  currentStep,
  totalSteps = 4,
  className,
}: ProgressIndicatorProps) {
  const [prevStep, setPrevStep] = useState(currentStep)
  const [mounted, setMounted] = useState(false)

  useEffect(() => {
    // 组件挂载后启动动画
    setMounted(true)
  }, [])

  useEffect(() => {
    setPrevStep(currentStep)
  }, [currentStep])

  return (
    <div
      className={cn('box-border flex w-full flex-row items-center justify-start gap-1', className)}
    >
      {Array.from({ length: totalSteps }).map((_, index) => {
        const isNewlyActive = index === currentStep - 1
        const wasActive = index < prevStep

        return (
          <div key={index} className="bg-surface-element-normal relative h-1 grow rounded-[999px]">
            {index < currentStep && (
              <div
                className={cn(
                  'bg-surface-white-normal absolute inset-0 rounded-full',
                  isNewlyActive && mounted && 'transition-[width,opacity] duration-500 ease-out',
                  isNewlyActive && !mounted ? 'w-0 opacity-0' : 'w-full opacity-100',
                  wasActive && 'w-full opacity-100'
                )}
              />
            )}
          </div>
        )
      })}
    </div>
  )
}
