"use client"
import * as SliderPrimitive from "@radix-ui/react-slider"
import React, { ComponentPropsWithoutRef, ElementRef, forwardRef } from "react"
import { disabledVariants } from "../../styles"
import { classNames } from "../../utils"
import { FlexCenter } from "../FlexCenter"

export type SliderProps = Omit<
  ComponentPropsWithoutRef<typeof SliderPrimitive.Root>,
  "defaultValue" | "value" | "onChange" | "onValueChange"
> & {
  defaultValue?: number
  value?: number
  onValueChange?: (value: number) => void
}

/**
 * An input where the user selects a value from within a given range.
 */
export const Slider = forwardRef<
  ElementRef<typeof SliderPrimitive.Root>,
  SliderProps
>(function Slider(
  {
    className,
    defaultValue,
    value,
    disabled,
    onValueChange,
    minStepsBetweenThumbs = 1,
    ...props
  },
  ref,
) {
  return (
    <FlexCenter
      className={classNames(
        disabledVariants({ disabled }),
        "w-full p-3",
        className,
      )}
    >
      <SliderPrimitive.Root
        className="relative flex w-full cursor-pointer touch-none select-none items-center"
        defaultValue={defaultValue !== undefined ? [defaultValue] : undefined}
        disabled={disabled}
        minStepsBetweenThumbs={minStepsBetweenThumbs}
        ref={ref}
        value={value !== undefined ? [value] : undefined}
        onValueChange={([value]) => {
          onValueChange?.(value)
        }}
        {...props}
      >
        <SliderPrimitive.Track
          className={classNames(
            "relative h-2 w-full grow overflow-hidden bg-bg-additional-2",
            "rounded-full",
          )}
        >
          <SliderPrimitive.Range className="absolute h-full bg-blue-3" />
        </SliderPrimitive.Track>
        <SliderPrimitive.Thumb
          className={classNames(
            "block size-4 rounded-full bg-blue-3 shadow-sm",
            "transition-colors",
          )}
        />
      </SliderPrimitive.Root>
    </FlexCenter>
  )
})
