import { FC, useEffect, useState } from 'react'
import { Slider } from '@/components/ui/slider'

interface PriceFilterProps {
    value: [number, number]
    onChange: (value: [number, number]) => void
    minMaxRange: [number, number] // Original min/max from API
}

const PriceFilter: FC<PriceFilterProps> = ({ value, onChange, minMaxRange }) => {

    const [minValue, setMinValue] = useState(value[0])
    const [maxValue, setMaxValue] = useState(value[1])
    const [hasUserChanged, setHasUserChanged] = useState(false)

    const handleChange = (newValue: [number, number]) => {
        const [min, max] = newValue
        if (min === minValue && max === maxValue) {
            return
        }
        setMinValue(min)
        setMaxValue(max)
        setHasUserChanged(true)
    }

    useEffect(() => {
        if (hasUserChanged && minValue && maxValue) {
            const timeout = setTimeout(() => {
                onChange([minValue, maxValue])
            }, 2000)
            return () => clearTimeout(timeout)
        }
    }, [minValue, maxValue, onChange, hasUserChanged])

    // Update current values when prop changes
    useEffect(() => {
        setMinValue(value[0])
        setMaxValue(value[1])
        setHasUserChanged(false)
    }, [value])

    return (
        <div className='space-y-4'>
            <div className='px-1'>
                <Slider
                    value={[minValue, maxValue]}
                    onValueChange={(newValue) => handleChange(newValue as [number, number])}
                    min={minMaxRange[0]}
                    max={minMaxRange[1]}
                    // step={10000}
                    className='w-full [&_[data-slot=slider-thumb]:first-of-type]:order-2 [&_[data-slot=slider-thumb]:last-of-type]:order-1'
                />
            </div>
            <div className='flex items-center justify-between text-sm text-[#666666]'>
                <span>{maxValue.toLocaleString('fa-IR')} تومان</span>
                <span>{minValue.toLocaleString('fa-IR')} تومان</span>
            </div>
        </div>
    )
}

export default PriceFilter
