import * as SliderPrimitive from '@radix-ui/react-slider'

import { cva, type VariantProps } from 'class-variance-authority'
import type { CSSProperties } from 'react'
import * as React from 'react'

import { cn } from '@lib/utils'

const sliderVariants = cva('absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full', {
  variants: {
    sliderVariant: {
      default: 'bg-primary',
      gray: 'bg-muted-foreground',
    },
  },
  defaultVariants: {
    sliderVariant: 'default',
  },
})

const knobVariants = cva(
  'bg-background block size-4 shrink-0 rounded-full border shadow-sm transition-[color,box-shadow]  focus-visible:outline-hidden disabled:pointer-events-none disabled:opacity-50',
  {
    variants: {
      knobVariant: {
        default: 'border-primary ring-ring/50 hover:ring-4 focus-visible:ring-4',
        gray: 'border-muted-foreground border-2',
      },
    },
    defaultVariants: {
      knobVariant: 'default',
    },
  },
)

type SliderProps = React.ComponentProps<typeof SliderPrimitive.Root> &
  VariantProps<typeof sliderVariants> &
  VariantProps<typeof knobVariants> & { knobSize?: number }

function Slider({
  className,
  defaultValue,
  value,
  min = 0,
  max = 100,
  sliderVariant,
  knobVariant,
  knobSize,
  ...props
}: SliderProps) {
  const _values = React.useMemo(() => {
    if (Array.isArray(value)) {
      return value
    } else if (Array.isArray(defaultValue)) {
      return defaultValue
    }
    return [min, max]
  }, [value, defaultValue, min, max])

  return (
    <SliderPrimitive.Root
      data-slot="slider"
      defaultValue={defaultValue}
      value={value}
      min={min}
      max={max}
      className={cn(
        'cursor-pointer relative flex w-full touch-none items-center select-none data-[disabled]:opacity-50 data-[orientation=vertical]:h-full data-[orientation=vertical]:min-h-44 data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col',
        className,
      )}
      {...props}
    >
      <SliderPrimitive.Track
        data-slot="slider-track"
        className={cn(
          'bg-muted relative grow overflow-hidden rounded-full data-[orientation=horizontal]:h-1.5 data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5',
        )}
      >
        <SliderPrimitive.Range data-slot="slider-range" className={cn(sliderVariants({ sliderVariant }))} />
      </SliderPrimitive.Track>
      {Array.from({ length: _values.length }, (_, index) => (
        <SliderPrimitive.Thumb
          data-slot="slider-thumb"
          key={index}
          className={cn(
            knobVariants({
              knobVariant,
            }),
            knobSize ? 'size-(--knob-size)' : '',
          )}
          style={{ '--knob-size': `${knobSize}px` } as CSSProperties}
        />
      ))}
    </SliderPrimitive.Root>
  )
}

export { Slider, sliderVariants, knobVariants }
