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

interface VoiceToneSliderProps {
  label: string
  value: number
  onChange?: (value: number) => void
  steps: number[] // 刻度值数组
}

export default function VoiceToneSlider({
  label,
  value = 0,
  onChange,
  steps,
}: VoiceToneSliderProps) {
  const sliderRef = useRef<HTMLDivElement>(null)
  const [isDragging, setIsDragging] = useState(false)

  // 如果 value 不在 steps 中，使用默认值 0
  const activeValue = steps.includes(value) ? value : 0

  // 计算当前值对应的位置
  const getValueFromPosition = (clientX: number) => {
    if (!sliderRef.current) return value

    const rect = sliderRef.current.getBoundingClientRect()
    const padding = 24 // px-6 = 24px
    const availableWidth = rect.width - padding * 2
    const position = clientX - rect.left - padding

    // 计算最接近的刻度索引
    const normalizedPosition = Math.max(0, Math.min(1, position / availableWidth))
    const stepIndex = Math.round(normalizedPosition * (steps.length - 1))
    return steps[stepIndex]
  }

  // 处理鼠标按下
  const handleMouseDown = (e: React.MouseEvent) => {
    setIsDragging(true)
    const newValue = getValueFromPosition(e.clientX)
    onChange?.(newValue)
  }

  // 处理鼠标移动
  const handleMouseMove = (e: MouseEvent) => {
    if (!isDragging) return
    const newValue = getValueFromPosition(e.clientX)
    onChange?.(newValue)
  }

  // 处理鼠标释放
  const handleMouseUp = () => {
    setIsDragging(false)
  }

  // 添加全局鼠标事件监听
  useEffect(() => {
    if (isDragging) {
      document.addEventListener('mousemove', handleMouseMove)
      document.addEventListener('mouseup', handleMouseUp)

      return () => {
        document.removeEventListener('mousemove', handleMouseMove)
        document.removeEventListener('mouseup', handleMouseUp)
      }
    }
  }, [isDragging])

  // 处理点击刻度点
  const handleDotClick = (index: number, e: React.MouseEvent) => {
    e.stopPropagation()
    onChange?.(steps[index])
  }

  return (
    <div className="flex flex-col gap-1">
      <div className="text-txt-secondary-normal txt-label-s flex justify-between">
        <span>{label === 'Pitch' ? 'Low' : 'Slow'}</span>
        <span>{label === 'Pitch' ? 'High' : 'Fast'}</span>
      </div>
      <div
        ref={sliderRef}
        className="bg-surface-element-normal flex h-12 cursor-pointer items-center justify-between rounded-sm px-6 py-3 select-none"
        onMouseDown={handleMouseDown}
      >
        {steps.map((stepValue, index) => {
          const isActive = stepValue === activeValue

          return (
            <div
              key={index}
              className="flex cursor-pointer items-center justify-center"
              onClick={(e) => handleDotClick(index, e)}
            >
              <div className="flex h-6 w-2 items-center justify-center">
                <div
                  className={cn(
                    'h-full rounded-full border-solid transition-all',
                    isActive
                      ? 'bg-primary-normal w-full'
                      : 'bg-outline-normal hover:bg-primary-variant-normal w-[2px]'
                  )}
                />
              </div>
            </div>
          )
        })}
      </div>
    </div>
  )
}
