import React, { ChangeEvent, useEffect, useState } from 'react';

interface MultiRangeFilterProps {
  min: number;
  max: number;
  selectedMin: number;
  selectedMax: number;

  valueFormatter: (value: number) => string;
  onChange: (min: number, max: number) => void;
}

const MultiRangeFilter: React.FC<MultiRangeFilterProps> = ({ min, max, selectedMin, selectedMax, valueFormatter, onChange }) => {
  const [isDragging, setIsDragging] = useState(false);
  const [leftPercentage, setLeftPercentage] = useState<number>(0);
  const [rightPercentage, setRightPercentage] = useState<number>(0);
  const [minVal, setMinVal] = useState(min);
  const [maxVal, setMaxVal] = useState(max);
  const minGap = 5;

  useEffect(() => {
    setSliderTrack();
  }, [minVal, maxVal]);

  const slideMin = (e: ChangeEvent<HTMLInputElement>) => {
    const value = parseInt(e.target.value, 10);
    if (value >= min && selectedMax - value >= minGap) {
      setMinVal(value);
    }
  };

  const slideMax = (e: ChangeEvent<HTMLInputElement>) => {
    const value = parseInt(e.target.value, 10);
    if (value <= max && value - selectedMin >= minGap) {
      setMaxVal(value);
    }
  };

  const setSliderTrack = () => {
    const range = document.querySelector('.slider-track');

    if (range) {
      const minPercent = ((minVal - min) / (max - min)) * 100;
      const maxPercent = ((maxVal - min) / (max - min)) * 100;

      setLeftPercentage(minPercent);
      setRightPercentage(100 - maxPercent);
    }
  };

  const startDrag = () => {
    setIsDragging(true);
  };

  const stopDrag = () => {
    setIsDragging(false);
    onChange(minVal, maxVal);
  };

  return (
    <div className="double-slider-box">
      <div className="input-box">
        <div className="min-box">{valueFormatter(min)}</div>
        <div className="max-box">{valueFormatter(max)}</div>
      </div>
      <div className="range-slider">
        <div className="slider-track" style={{ left: leftPercentage + '%', right: rightPercentage + '%' }}></div>
        <input
          type="range"
          min={min}
          max={max}
          value={minVal}
          onChange={slideMin}
          onMouseDown={startDrag}
          onMouseUp={stopDrag}
          onTouchStart={startDrag}
          onTouchEnd={stopDrag}
          className="min-val"
        />
        <input
          type="range"
          min={min}
          max={max}
          value={maxVal}
          onChange={slideMax}
          onMouseDown={startDrag}
          onMouseUp={stopDrag}
          onTouchStart={startDrag}
          onTouchEnd={stopDrag}
          className="max-val"
        />
        {isDragging && <div className="min-tooltip">{valueFormatter(minVal)}</div>}
        {isDragging && <div className="max-tooltip">{valueFormatter(maxVal)}</div>}
      </div>
    </div>
  );
};

export default MultiRangeFilter;
