'use client'
import React, { useState, useEffect, useCallback } from "react";
import { Range, getTrackBackground } from "react-range";
import { useFilter } from "@/stores/productsFilter";

export default function PriceSlider() {
  const { setPriceRange } = useFilter();
  const [values, setValues] = useState([0, 10000]);
  const [debouncedValues, setDebouncedValues] = useState(values);
  const min = 0;
  const max = 10000;

  // Handle changes immediately, but don't trigger the fetch
  const handleChange = (values) => {
    setValues(values);
  };

  // Debounce effect to trigger only when user stops scrolling
  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedValues(values);
    }, 300); // Adjust the delay as needed

    return () => clearTimeout(handler);
  }, [values]);

  // Update filter only on debounced value change
  useEffect(() => {
    setPriceRange(debouncedValues[0], debouncedValues[1]);
  }, [debouncedValues]);

  return (
    <div dir="ltr" className="w-full px-4 py-6">
      <Range
        values={values}
        step={1}
        min={min}
        max={max}
        onChange={handleChange}
        renderTrack={({ props, children }) => (
          <div
            {...props}
            className="w-full h-[3px] bg-gray-300 rounded-md"
            style={{
              background: getTrackBackground({
                values,
                colors: ["#ccc", "#000000", "#ccc"],
                min,
                max,
              }),
            }}
          >
            {children}
          </div>
        )}
        renderThumb={({ props }) => (
          <div {...props} className="size-3 bg-white border-2 border-black rounded-full" />
        )}
      />
      <div className="flex items-center justify-between gap-2 mt-2">
        <div>
          <p className="text-gray-400 text-sm text-end">الاقل</p>
          <span className="border-2 border-gray-400 text-gray-400 rounded-sm flex items-center justify-center px-4 py-1"> {values[0]}</span>
        </div>
        <div>
          <p className="text-gray-400 text-sm text-end">الاعلي</p>
          <span className="border-2 border-gray-400 text-gray-400 rounded-sm flex items-center justify-center px-4 py-1"> {values[1]}</span>
        </div>
      </div>
    </div>
  );
}
