/* eslint-disable react-hooks/exhaustive-deps */
import { useEffect, useRef, useState } from "react";

interface RangeInputProps {
  max?: number;
  min?: number;
  value?: number;
  onChange: (value: number) => void;
}

function RangeInput({
  onChange,
  value = 50,
  max = 100,
  min = 0,
}: RangeInputProps) {
  const [mouseDown, setMouseDown] = useState(false);

  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    addEventListener("mouseup", () => setMouseDown(false));
    addEventListener("mousemove", handleMouseMove);
    return () => {
      removeEventListener("mouseup", () => setMouseDown(false));
      removeEventListener("mousemove", handleMouseMove);
    };
  }, [handleMouseMove]);

  function handleMouseMove(e: MouseEvent) {
    if (mouseDown && ref.current) {
      onChange(
        Math.min(
          Math.max(
            min,
            ((e.clientX - ref.current.getBoundingClientRect().left) /
              ref.current.clientWidth) *
              (max - min) +
              min
          ),
          max
        )
      );
    }
  }

  function handleMouseDown(e: React.MouseEvent<HTMLDivElement>) {
    e.preventDefault();
    if (ref.current) {
      onChange(
        Math.min(
          Math.max(
            min,
            ((e.clientX - ref.current.getBoundingClientRect().left) /
              ref.current.clientWidth) *
              (max - min) +
              min
          ),
          max
        )
      );
    }
    setMouseDown(true);
  }

  return (
    <div
      ref={ref}
      className="2xl:w-[21.111vw] w-[304px] 2xl:h-[0.139vw] h-[2px] relative bg-[#F0F0F0] 2xl:rounded-[0.556vw] rounded-lg cursor-grab active:cursor-grabbing"
      onMouseDown={handleMouseDown}
    >
      <div
        className="bg-[#7B60F3] 2xl:rounded-[0.556vw] h-full absolute left-0 top-0 rounded-lg"
        style={{ width: `${((value - min) / (max - min)) * 100}%` }}
      />
      <div
        className="2xl:size-[0.833vw] size-3 rounded-full bg-[#7B60F3] absolute top-1/2 -translate-y-1/2 -translate-x-1/2"
        style={{ left: `${((value - min) / (max - min)) * 100}%` }}
      />
    </div>
  );
}

export default RangeInput;
