'use client'

import { formatPurchaseQuantity } from '@/app/[name]/(Main)/types/Types'
import { ef } from '@/lib/helpers/utfNumbers'
import { cn } from '@/lib/utils'
import * as SliderPrimitive from '@radix-ui/react-slider'
import { useCallback, useEffect, useRef, useState } from 'react'

interface VariableWeightSliderProps {
  value: number
  min: number
  max: number
  step: number
  purchaseUnit?: string
  onChange: (value: number) => void
  onCommit?: (value: number) => void
  className?: string
}

export function VariableWeightSlider({
  value,
  min,
  max,
  step,
  purchaseUnit,
  onChange,
  onCommit,
  className,
}: VariableWeightSliderProps) {
  const rootRef = useRef<HTMLDivElement>(null)
  const [tooltipLeft, setTooltipLeft] = useState(0)

  const updateTooltipPosition = useCallback(() => {
    const root = rootRef.current
    if (!root) return
    const thumb = root.querySelector<HTMLElement>('[data-slot="slider-thumb"]')
    if (!thumb) return
    const rootRect = root.getBoundingClientRect()
    const thumbRect = thumb.getBoundingClientRect()
    setTooltipLeft(thumbRect.left - rootRect.left + thumbRect.width / 2)
  }, [])

  useEffect(() => {
    updateTooltipPosition()
    window.addEventListener('resize', updateTooltipPosition)
    return () => window.removeEventListener('resize', updateTooltipPosition)
  }, [value, min, max, updateTooltipPosition])

  const quantityLabel = ef(formatPurchaseQuantity(value, purchaseUnit))

  return (
    <div ref={rootRef} className={cn('relative w-full', className)}>
      <div
        className="pointer-events-none absolute -top-10 z-10 -translate-x-1/2 whitespace-nowrap rounded-lg bg-[#EAECF0] px-3.5 py-1.5 text-xs font-semibold text-foreground"
        style={{ left: tooltipLeft }}
      >
        {quantityLabel}
      </div>

      <SliderPrimitive.Root
        data-slot="slider"
        value={[value]}
        min={min}
        max={max}
        step={step}
        onValueChange={(values) => onChange(values[0] ?? min)}
        onValueCommit={(values) => onCommit?.(values[0] ?? min)}
        className="relative flex w-full touch-none select-none items-center py-3"
      >
        <SliderPrimitive.Track
          data-slot="slider-track"
          className="relative h-[3px] w-full grow overflow-hidden rounded-full bg-[#EAECF0]"
        >
          <SliderPrimitive.Range
            data-slot="slider-range"
            className="absolute h-full bg-black"
          />
        </SliderPrimitive.Track>
        <SliderPrimitive.Thumb
          data-slot="slider-thumb"
          className="block size-5 shrink-0 cursor-grab rounded-full bg-black shadow-none outline-none active:cursor-grabbing focus-visible:ring-0"
        />
      </SliderPrimitive.Root>
    </div>
  )
}
