import React from 'react';
import { Slider, InputNumber } from 'antd';
import { SliderBaseProps } from 'antd/lib/slider';

export interface SliderInputProp extends SliderBaseProps {
  value?: number;
  showInput?: boolean;
  onChange?: (value: number) => void;
}

const SliderInput: React.FC<SliderInputProp> = function ({
  min,
  max,
  value,
  step,
  showInput = true,
  onChange,
  ...props
}) {
  const [innerValue, setInnerValue] = React.useState<number>(0);

  React.useEffect(() => {
    setInnerValue(value || 0);
  }, [value]);

  const handleChange = (e: number | React.ChangeEvent<HTMLInputElement> | null) => {
    const value: number = e === null ? 0 : typeof e === 'number' ? e : Number(e.target.value);

    setInnerValue(value);
    onChange?.(value);
  };

  return (
    <div className="flex gap-x-2">
      <Slider
        className={showInput ? '!w-2/3' : '!w-full'}
        min={min}
        max={max}
        step={step}
        value={innerValue}
        onChange={setInnerValue}
        onAfterChange={handleChange}
        {...props}
      />
      {showInput && (
        <InputNumber
          className="w-1/3"
          min={min}
          max={max}
          step={step || 0.1}
          value={innerValue}
          onChange={handleChange}
        />
      )}
    </div>
  );
};

export default SliderInput;
