import { useState, useCallback, useRef, useEffect } from 'react'

// Global ref to store animation functions
const animationRef = { startAnimation: null, stopAnimation: null }

/**
 * Create animation control functions
 */
export function useUpdateBtnAnimation(btnRef, externalLoading, onClick, disabled) {
  const [internalLoading, setInternalLoading] = useState(false)
  
  const isLoading = externalLoading !== undefined ? externalLoading : internalLoading
  
  // Start animation
  const startAnimation = useCallback(() => {
    if (externalLoading === undefined) setInternalLoading(true)
  }, [externalLoading])

  // Stop animation
  const stopAnimation = useCallback(() => {
    if (externalLoading === undefined) setInternalLoading(false)
  }, [externalLoading])
  
  // Update global ref with latest functions
  useEffect(() => {
    animationRef.startAnimation = startAnimation
    animationRef.stopAnimation = stopAnimation
  }, [startAnimation, stopAnimation])
  
  // Handle button click
  const handleClick = useCallback(async (e) => {
    if (disabled || isLoading) return
    const self = { startAnimation, stopAnimation }
    const result = onClick?.(e, self)
    if (result?.then) await result
  }, [onClick, disabled, isLoading, startAnimation, stopAnimation])
  
  return { isLoading, startAnimation, stopAnimation, handleClick }
}

// Export animation functions for direct access
export function getStartAnimation() {
  return animationRef.startAnimation
}

export function getStopAnimation() {
  return animationRef.stopAnimation
}
