import React, { useState } from "react"
import Slider from "../slider"
import Label from "../label"

export default function PixelSlider({
  label,
  name,
  value,
  onChange,
  min = 0,
  max,
  step,
  showUnit = true,
}) {
  const [sliderValue, setSliderValue] = useState(value)

  function handleChange(e) {
    const newValue = Number(e.target.value)

    if (isNaN(newValue)) return

    setSliderValue(newValue)
    onChange(newValue)
  }

  return (
    <div>
      {label && (
        <Label className="mb-1" htmlFor={name}>
          {label}
        </Label>
      )}

      <div className="grid grid-cols-3 gap-4">
        <Slider
          type="range"
          className="col-span-2"
          value={sliderValue}
          onChange={handleChange}
          min={min}
          max={max}
          step={step}
        />

        <div className="w-full relative">
          <input
            id={name}
            name={name}
            className="block border rounded w-full p-2 border-gray-200 text-gray-700 text-sm focus:outline-blue"
            value={sliderValue}
            onChange={handleChange}
            min={min}
            max={max}
            style={{ lineHeight: "22px" }}
          />
          {showUnit && (
            <span className="absolute right-0 top-0 bottom-0 flex items-center p-2 text-gray-700 text-sm pointer-events-none">
              px
            </span>
          )}
        </div>
      </div>
    </div>
  )
}
