import React, { useEffect, useState } from "react";

interface InputToggleProps {
  label: string; 
  min?: number;
  max?: number;
  step?: number; // Added step prop
  onClick?: () => void; 
  onChange?: (value: number) => void; 
  disabled?: boolean;
  value?: number;
  onPointerUp?: (value: number) => void;
}

const InputRange: React.FC<InputToggleProps> = ({
  label,
  onClick,
  onChange,
  min,
  max,
  step = 1, // default step
  disabled,
  value,
  onPointerUp,
}) => {
  const [rangeValue, setRangeValue] = useState<number>(value ?? 5);

  function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
    const newValue = parseFloat(e.target.value); 
    setRangeValue(newValue);

    if (onChange) onChange(newValue);
  }

  useEffect(() => {
    if (value !== undefined) setRangeValue(value);
  }, [value]);

  function handlePointerUp(e: React.PointerEvent<HTMLInputElement>) {
    const newValue = parseFloat(e.currentTarget.value);
    if (onPointerUp) onPointerUp(newValue);
  }

  function handleKey(e: React.KeyboardEvent<HTMLInputElement>) {
    const newValue = parseFloat(e.currentTarget.value);
    if (onPointerUp) onPointerUp(newValue);
  }

  return (
    <div className="input-range-container">
      <label htmlFor={`range-input-${value}`} className="label" onClick={onClick}>
        {label}
      </label>
      <div className="input-container">
        <input
          id={`range-input-${value}`}
          type="range"
          min={min}
          max={max}
          step={step} // added here
          onChange={handleChange}
          disabled={disabled}
          value={rangeValue}
          onPointerUp={handlePointerUp}
        />
        <input
          type="number"
          min={min}
          max={max}
          step={step} // added here
          value={rangeValue}
          onChange={handleChange}
          disabled={disabled}
          className="input-value"
          onKeyUp={(e) => {
            if (e.key === "ArrowUp" || e.key === "ArrowDown") handleKey(e);
          }}
        />
      </div>
    </div>
  );
};

export default InputRange;
