import { useState, useEffect } from 'react'

/**
 * Custom hook for debouncing values to prevent excessive re-renders
 * 
 * @param value - The value to debounce
 * @param delay - The delay in milliseconds
 * @returns The debounced value
 */
export function useDebounce<T>(value: T, delay: number): T {
  const [debouncedValue, setDebouncedValue] = useState<T>(value)

  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedValue(value)
    }, delay)

    return () => {
      clearTimeout(handler)
    }
  }, [value, delay])

  return debouncedValue
}

/**
 * Custom hook for throttling function calls
 * 
 * @param callback - The function to throttle
 * @param delay - The delay in milliseconds
 * @returns The throttled function
 */
export function useThrottle<T extends (...args: any[]) => any>(
  callback: T,
  delay: number
): T {
  const [lastCall, setLastCall] = useState<number>(0)

  const throttledCallback = ((...args: Parameters<T>) => {
    const now = Date.now()
    if (now - lastCall >= delay) {
      setLastCall(now)
      return callback(...args)
    }
  }) as T

  return throttledCallback
}

/**
 * Custom hook for preventing rapid state updates
 * 
 * @param initialValue - Initial state value
 * @param delay - Minimum delay between updates in milliseconds
 * @returns [state, setState] tuple
 */
export function useThrottledState<T>(
  initialValue: T,
  delay: number = 100
): [T, (value: T) => void] {
  const [state, setState] = useState<T>(initialValue)
  const [lastUpdate, setLastUpdate] = useState<number>(0)

  const setThrottledState = (value: T) => {
    const now = Date.now()
    if (now - lastUpdate >= delay) {
      setState(value)
      setLastUpdate(now)
    }
  }

  return [state, setThrottledState]
}
