import React, { useState, useEffect } from "react"
import cx from "classnames"

const STATES = {
  default: "border-gray-200 focus-within:outline-blue",
  error: "border-red-600 outline-red",
  success: "border-green-600 outline-green",
}

function Slider({
  name,
  state = "default",
  className,
  onInput,
  onChange,
  value,
  ...props
}) {
  className = cx(
    className,
    "design-slider px-2 py-2 flex items-center border rounded",
    STATES[state]
  )

  useEffect(() => {
    if (typeof value === "object") return
    setRangeValue(value)
  }, [value])

  const [rangeValue, setRangeValue] = useState(
    typeof value !== "undefined" ? value : props.min || 0
  )

  function updateProgress(event) {
    setRangeValue(event.target.value)
    if (onInput) {
      onInput(event)
    }
  }

  return (
    <div
      className={className}
      style={{
        transition: "border-color 0.3s, box-shadow 0.3s",
        "--min": props.min,
        "--max": props.max,
        "--rangeValue": rangeValue,
      }}
    >
      <input
        name={name}
        type="range"
        onInput={updateProgress}
        onChange={onChange}
        value={rangeValue}
        {...props}
      />
    </div>
  )
}

export default Slider
